babylon.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907
  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.4";
  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. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18483. _this.scalingDeterminant = 1;
  18484. _this.infiniteDistance = false;
  18485. /**
  18486. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18487. * By default the system will update normals to compensate
  18488. */
  18489. _this.ignoreNonUniformScaling = false;
  18490. _this.position = BABYLON.Vector3.Zero();
  18491. _this._localWorld = BABYLON.Matrix.Zero();
  18492. _this._worldMatrix = BABYLON.Matrix.Zero();
  18493. _this._worldMatrixDeterminant = 0;
  18494. _this._absolutePosition = BABYLON.Vector3.Zero();
  18495. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18496. _this._postMultiplyPivotMatrix = false;
  18497. _this._isWorldMatrixFrozen = false;
  18498. /**
  18499. * An event triggered after the world matrix is updated
  18500. */
  18501. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18502. _this._nonUniformScaling = false;
  18503. if (isPure) {
  18504. _this.getScene().addTransformNode(_this);
  18505. }
  18506. return _this;
  18507. }
  18508. /**
  18509. * Gets a string idenfifying the name of the class
  18510. * @returns "TransformNode" string
  18511. */
  18512. TransformNode.prototype.getClassName = function () {
  18513. return "TransformNode";
  18514. };
  18515. Object.defineProperty(TransformNode.prototype, "rotation", {
  18516. /**
  18517. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18518. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18519. * Default : (0.0, 0.0, 0.0)
  18520. */
  18521. get: function () {
  18522. return this._rotation;
  18523. },
  18524. set: function (newRotation) {
  18525. this._rotation = newRotation;
  18526. },
  18527. enumerable: true,
  18528. configurable: true
  18529. });
  18530. Object.defineProperty(TransformNode.prototype, "scaling", {
  18531. /**
  18532. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18533. * Default : (1.0, 1.0, 1.0)
  18534. */
  18535. get: function () {
  18536. return this._scaling;
  18537. },
  18538. /**
  18539. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18540. * Default : (1.0, 1.0, 1.0)
  18541. */
  18542. set: function (newScaling) {
  18543. this._scaling = newScaling;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18549. /**
  18550. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18551. * It's null by default.
  18552. * 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)
  18553. */
  18554. get: function () {
  18555. return this._rotationQuaternion;
  18556. },
  18557. set: function (quaternion) {
  18558. this._rotationQuaternion = quaternion;
  18559. //reset the rotation vector.
  18560. if (quaternion && this.rotation.length()) {
  18561. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18562. }
  18563. },
  18564. enumerable: true,
  18565. configurable: true
  18566. });
  18567. Object.defineProperty(TransformNode.prototype, "forward", {
  18568. /**
  18569. * The forward direction of that transform in world space.
  18570. */
  18571. get: function () {
  18572. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18573. },
  18574. enumerable: true,
  18575. configurable: true
  18576. });
  18577. Object.defineProperty(TransformNode.prototype, "up", {
  18578. /**
  18579. * The up direction of that transform in world space.
  18580. */
  18581. get: function () {
  18582. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18583. },
  18584. enumerable: true,
  18585. configurable: true
  18586. });
  18587. Object.defineProperty(TransformNode.prototype, "right", {
  18588. /**
  18589. * The right direction of that transform in world space.
  18590. */
  18591. get: function () {
  18592. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18593. },
  18594. enumerable: true,
  18595. configurable: true
  18596. });
  18597. /**
  18598. * Returns the latest update of the World matrix
  18599. * Returns a Matrix.
  18600. */
  18601. TransformNode.prototype.getWorldMatrix = function () {
  18602. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18603. this.computeWorldMatrix();
  18604. }
  18605. return this._worldMatrix;
  18606. };
  18607. /** @hidden */
  18608. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18609. return this._worldMatrixDeterminant;
  18610. };
  18611. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18612. /**
  18613. * Returns directly the latest state of the mesh World matrix.
  18614. * A Matrix is returned.
  18615. */
  18616. get: function () {
  18617. return this._worldMatrix;
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. /**
  18623. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18624. * Returns the TransformNode.
  18625. */
  18626. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18627. this._poseMatrix.copyFrom(matrix);
  18628. return this;
  18629. };
  18630. /**
  18631. * Returns the mesh Pose matrix.
  18632. * Returned object : Matrix
  18633. */
  18634. TransformNode.prototype.getPoseMatrix = function () {
  18635. return this._poseMatrix;
  18636. };
  18637. TransformNode.prototype._isSynchronized = function () {
  18638. if (this._isDirty) {
  18639. return false;
  18640. }
  18641. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18642. return false;
  18643. if (this._cache.pivotMatrixUpdated) {
  18644. return false;
  18645. }
  18646. if (this.infiniteDistance) {
  18647. return false;
  18648. }
  18649. if (!this._cache.position.equals(this.position))
  18650. return false;
  18651. if (this.rotationQuaternion) {
  18652. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18653. return false;
  18654. }
  18655. if (!this._cache.rotation.equals(this.rotation))
  18656. return false;
  18657. if (!this._cache.scaling.equals(this.scaling))
  18658. return false;
  18659. return true;
  18660. };
  18661. TransformNode.prototype._initCache = function () {
  18662. _super.prototype._initCache.call(this);
  18663. this._cache.localMatrixUpdated = false;
  18664. this._cache.position = BABYLON.Vector3.Zero();
  18665. this._cache.scaling = BABYLON.Vector3.Zero();
  18666. this._cache.rotation = BABYLON.Vector3.Zero();
  18667. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18668. this._cache.billboardMode = -1;
  18669. };
  18670. TransformNode.prototype.markAsDirty = function (property) {
  18671. if (property === "rotation") {
  18672. this.rotationQuaternion = null;
  18673. }
  18674. this._currentRenderId = Number.MAX_VALUE;
  18675. this._isDirty = true;
  18676. return this;
  18677. };
  18678. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18679. /**
  18680. * Returns the current mesh absolute position.
  18681. * Retuns a Vector3.
  18682. */
  18683. get: function () {
  18684. return this._absolutePosition;
  18685. },
  18686. enumerable: true,
  18687. configurable: true
  18688. });
  18689. /**
  18690. * Sets a new matrix to apply before all other transformation
  18691. * @param matrix defines the transform matrix
  18692. * @returns the current TransformNode
  18693. */
  18694. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18695. return this.setPivotMatrix(matrix, false);
  18696. };
  18697. /**
  18698. * Sets a new pivot matrix to the current node
  18699. * @param matrix defines the new pivot matrix to use
  18700. * @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
  18701. * @returns the current TransformNode
  18702. */
  18703. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18704. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18705. this._pivotMatrix = matrix.clone();
  18706. this._cache.pivotMatrixUpdated = true;
  18707. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18708. if (this._postMultiplyPivotMatrix) {
  18709. if (!this._pivotMatrixInverse) {
  18710. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18711. }
  18712. else {
  18713. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18714. }
  18715. }
  18716. return this;
  18717. };
  18718. /**
  18719. * Returns the mesh pivot matrix.
  18720. * Default : Identity.
  18721. * A Matrix is returned.
  18722. */
  18723. TransformNode.prototype.getPivotMatrix = function () {
  18724. return this._pivotMatrix;
  18725. };
  18726. /**
  18727. * Prevents the World matrix to be computed any longer.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.freezeWorldMatrix = function () {
  18731. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18732. this.computeWorldMatrix(true);
  18733. this._isWorldMatrixFrozen = true;
  18734. return this;
  18735. };
  18736. /**
  18737. * Allows back the World matrix computation.
  18738. * Returns the TransformNode.
  18739. */
  18740. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18741. this._isWorldMatrixFrozen = false;
  18742. this.computeWorldMatrix(true);
  18743. return this;
  18744. };
  18745. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18746. /**
  18747. * True if the World matrix has been frozen.
  18748. * Returns a boolean.
  18749. */
  18750. get: function () {
  18751. return this._isWorldMatrixFrozen;
  18752. },
  18753. enumerable: true,
  18754. configurable: true
  18755. });
  18756. /**
  18757. * Retuns the mesh absolute position in the World.
  18758. * Returns a Vector3.
  18759. */
  18760. TransformNode.prototype.getAbsolutePosition = function () {
  18761. this.computeWorldMatrix();
  18762. return this._absolutePosition;
  18763. };
  18764. /**
  18765. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18766. * Returns the TransformNode.
  18767. */
  18768. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18769. if (!absolutePosition) {
  18770. return this;
  18771. }
  18772. var absolutePositionX;
  18773. var absolutePositionY;
  18774. var absolutePositionZ;
  18775. if (absolutePosition.x === undefined) {
  18776. if (arguments.length < 3) {
  18777. return this;
  18778. }
  18779. absolutePositionX = arguments[0];
  18780. absolutePositionY = arguments[1];
  18781. absolutePositionZ = arguments[2];
  18782. }
  18783. else {
  18784. absolutePositionX = absolutePosition.x;
  18785. absolutePositionY = absolutePosition.y;
  18786. absolutePositionZ = absolutePosition.z;
  18787. }
  18788. if (this.parent) {
  18789. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18790. invertParentWorldMatrix.invert();
  18791. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18792. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18793. }
  18794. else {
  18795. this.position.x = absolutePositionX;
  18796. this.position.y = absolutePositionY;
  18797. this.position.z = absolutePositionZ;
  18798. }
  18799. return this;
  18800. };
  18801. /**
  18802. * Sets the mesh position in its local space.
  18803. * Returns the TransformNode.
  18804. */
  18805. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18806. this.computeWorldMatrix();
  18807. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18808. return this;
  18809. };
  18810. /**
  18811. * Returns the mesh position in the local space from the current World matrix values.
  18812. * Returns a new Vector3.
  18813. */
  18814. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18815. this.computeWorldMatrix();
  18816. var invLocalWorldMatrix = this._localWorld.clone();
  18817. invLocalWorldMatrix.invert();
  18818. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18819. };
  18820. /**
  18821. * Translates the mesh along the passed Vector3 in its local space.
  18822. * Returns the TransformNode.
  18823. */
  18824. TransformNode.prototype.locallyTranslate = function (vector3) {
  18825. this.computeWorldMatrix(true);
  18826. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18827. return this;
  18828. };
  18829. /**
  18830. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18831. * @param targetPoint the position (must be in same space as current mesh) to look at
  18832. * @param yawCor optional yaw (y-axis) correction in radians
  18833. * @param pitchCor optional pitch (x-axis) correction in radians
  18834. * @param rollCor optional roll (z-axis) correction in radians
  18835. * @param space the choosen space of the target
  18836. * @returns the TransformNode.
  18837. */
  18838. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18839. if (yawCor === void 0) { yawCor = 0; }
  18840. if (pitchCor === void 0) { pitchCor = 0; }
  18841. if (rollCor === void 0) { rollCor = 0; }
  18842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18843. var dv = TransformNode._lookAtVectorCache;
  18844. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18845. targetPoint.subtractToRef(pos, dv);
  18846. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18847. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18848. var pitch = Math.atan2(dv.y, len);
  18849. if (this.rotationQuaternion) {
  18850. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18851. }
  18852. else {
  18853. this.rotation.x = pitch + pitchCor;
  18854. this.rotation.y = yaw + yawCor;
  18855. this.rotation.z = rollCor;
  18856. }
  18857. return this;
  18858. };
  18859. /**
  18860. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18861. * This Vector3 is expressed in the World space.
  18862. */
  18863. TransformNode.prototype.getDirection = function (localAxis) {
  18864. var result = BABYLON.Vector3.Zero();
  18865. this.getDirectionToRef(localAxis, result);
  18866. return result;
  18867. };
  18868. /**
  18869. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18870. * localAxis is expressed in the mesh local space.
  18871. * result is computed in the Wordl space from the mesh World matrix.
  18872. * Returns the TransformNode.
  18873. */
  18874. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18875. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18876. return this;
  18877. };
  18878. /**
  18879. * Sets a new pivot point to the current node
  18880. * @param point defines the new pivot point to use
  18881. * @param space defines if the point is in world or local space (local by default)
  18882. * @returns the current TransformNode
  18883. */
  18884. TransformNode.prototype.setPivotPoint = function (point, space) {
  18885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18886. if (this.getScene().getRenderId() == 0) {
  18887. this.computeWorldMatrix(true);
  18888. }
  18889. var wm = this.getWorldMatrix();
  18890. if (space == BABYLON.Space.WORLD) {
  18891. var tmat = BABYLON.Tmp.Matrix[0];
  18892. wm.invertToRef(tmat);
  18893. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18894. }
  18895. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18896. };
  18897. /**
  18898. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18899. */
  18900. TransformNode.prototype.getPivotPoint = function () {
  18901. var point = BABYLON.Vector3.Zero();
  18902. this.getPivotPointToRef(point);
  18903. return point;
  18904. };
  18905. /**
  18906. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18907. * Returns the TransformNode.
  18908. */
  18909. TransformNode.prototype.getPivotPointToRef = function (result) {
  18910. result.x = -this._pivotMatrix.m[12];
  18911. result.y = -this._pivotMatrix.m[13];
  18912. result.z = -this._pivotMatrix.m[14];
  18913. return this;
  18914. };
  18915. /**
  18916. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18917. */
  18918. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18919. var point = BABYLON.Vector3.Zero();
  18920. this.getAbsolutePivotPointToRef(point);
  18921. return point;
  18922. };
  18923. /**
  18924. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18925. * Returns the TransformNode.
  18926. */
  18927. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18928. result.x = this._pivotMatrix.m[12];
  18929. result.y = this._pivotMatrix.m[13];
  18930. result.z = this._pivotMatrix.m[14];
  18931. this.getPivotPointToRef(result);
  18932. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18933. return this;
  18934. };
  18935. /**
  18936. * Defines the passed node as the parent of the current node.
  18937. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18938. * Returns the TransformNode.
  18939. */
  18940. TransformNode.prototype.setParent = function (node) {
  18941. if (node === null) {
  18942. var rotation = BABYLON.Tmp.Quaternion[0];
  18943. var position = BABYLON.Tmp.Vector3[0];
  18944. var scale = BABYLON.Tmp.Vector3[1];
  18945. if (this.parent && this.parent.computeWorldMatrix) {
  18946. this.parent.computeWorldMatrix(true);
  18947. }
  18948. this.computeWorldMatrix(true);
  18949. this.getWorldMatrix().decompose(scale, rotation, position);
  18950. if (this.rotationQuaternion) {
  18951. this.rotationQuaternion.copyFrom(rotation);
  18952. }
  18953. else {
  18954. rotation.toEulerAnglesToRef(this.rotation);
  18955. }
  18956. this.scaling.x = scale.x;
  18957. this.scaling.y = scale.y;
  18958. this.scaling.z = scale.z;
  18959. this.position.x = position.x;
  18960. this.position.y = position.y;
  18961. this.position.z = position.z;
  18962. }
  18963. else {
  18964. var rotation = BABYLON.Tmp.Quaternion[0];
  18965. var position = BABYLON.Tmp.Vector3[0];
  18966. var scale = BABYLON.Tmp.Vector3[1];
  18967. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18968. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18969. this.computeWorldMatrix(true);
  18970. node.computeWorldMatrix(true);
  18971. node.getWorldMatrix().invertToRef(invParentMatrix);
  18972. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18973. diffMatrix.decompose(scale, rotation, position);
  18974. if (this.rotationQuaternion) {
  18975. this.rotationQuaternion.copyFrom(rotation);
  18976. }
  18977. else {
  18978. rotation.toEulerAnglesToRef(this.rotation);
  18979. }
  18980. this.position.x = position.x;
  18981. this.position.y = position.y;
  18982. this.position.z = position.z;
  18983. this.scaling.x = scale.x;
  18984. this.scaling.y = scale.y;
  18985. this.scaling.z = scale.z;
  18986. }
  18987. this.parent = node;
  18988. return this;
  18989. };
  18990. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18991. get: function () {
  18992. return this._nonUniformScaling;
  18993. },
  18994. enumerable: true,
  18995. configurable: true
  18996. });
  18997. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18998. if (this._nonUniformScaling === value) {
  18999. return false;
  19000. }
  19001. this._nonUniformScaling = value;
  19002. return true;
  19003. };
  19004. /**
  19005. * Attach the current TransformNode to another TransformNode associated with a bone
  19006. * @param bone Bone affecting the TransformNode
  19007. * @param affectedTransformNode TransformNode associated with the bone
  19008. */
  19009. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19010. this._transformToBoneReferal = affectedTransformNode;
  19011. this.parent = bone;
  19012. if (bone.getWorldMatrix().determinant() < 0) {
  19013. this.scalingDeterminant *= -1;
  19014. }
  19015. return this;
  19016. };
  19017. TransformNode.prototype.detachFromBone = function () {
  19018. if (!this.parent) {
  19019. return this;
  19020. }
  19021. if (this.parent.getWorldMatrix().determinant() < 0) {
  19022. this.scalingDeterminant *= -1;
  19023. }
  19024. this._transformToBoneReferal = null;
  19025. this.parent = null;
  19026. return this;
  19027. };
  19028. /**
  19029. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19030. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19031. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19032. * The passed axis is also normalized.
  19033. * Returns the TransformNode.
  19034. */
  19035. TransformNode.prototype.rotate = function (axis, amount, space) {
  19036. axis.normalize();
  19037. if (!this.rotationQuaternion) {
  19038. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19039. this.rotation = BABYLON.Vector3.Zero();
  19040. }
  19041. var rotationQuaternion;
  19042. if (!space || space === BABYLON.Space.LOCAL) {
  19043. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19044. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19045. }
  19046. else {
  19047. if (this.parent) {
  19048. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19049. invertParentWorldMatrix.invert();
  19050. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19051. }
  19052. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19053. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19054. }
  19055. return this;
  19056. };
  19057. /**
  19058. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19059. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19060. * The passed axis is also normalized.
  19061. * Returns the TransformNode.
  19062. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19063. */
  19064. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19065. axis.normalize();
  19066. if (!this.rotationQuaternion) {
  19067. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19068. this.rotation.copyFromFloats(0, 0, 0);
  19069. }
  19070. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19071. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19072. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19073. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19074. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19075. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19076. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19077. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19078. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19079. return this;
  19080. };
  19081. /**
  19082. * Translates the mesh along the axis vector for the passed distance in the given space.
  19083. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19084. * Returns the TransformNode.
  19085. */
  19086. TransformNode.prototype.translate = function (axis, distance, space) {
  19087. var displacementVector = axis.scale(distance);
  19088. if (!space || space === BABYLON.Space.LOCAL) {
  19089. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19090. this.setPositionWithLocalVector(tempV3);
  19091. }
  19092. else {
  19093. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19094. }
  19095. return this;
  19096. };
  19097. /**
  19098. * Adds a rotation step to the mesh current rotation.
  19099. * x, y, z are Euler angles expressed in radians.
  19100. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19101. * This means this rotation is made in the mesh local space only.
  19102. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19103. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19104. * ```javascript
  19105. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19106. * ```
  19107. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19108. * 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.
  19109. * Returns the TransformNode.
  19110. */
  19111. TransformNode.prototype.addRotation = function (x, y, z) {
  19112. var rotationQuaternion;
  19113. if (this.rotationQuaternion) {
  19114. rotationQuaternion = this.rotationQuaternion;
  19115. }
  19116. else {
  19117. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19118. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19119. }
  19120. var accumulation = BABYLON.Tmp.Quaternion[0];
  19121. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19122. rotationQuaternion.multiplyInPlace(accumulation);
  19123. if (!this.rotationQuaternion) {
  19124. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19125. }
  19126. return this;
  19127. };
  19128. /**
  19129. * Computes the mesh World matrix and returns it.
  19130. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19131. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19132. * If the parameter `force`is set to `true`, the actual computation is done.
  19133. * Returns the mesh World Matrix.
  19134. */
  19135. TransformNode.prototype.computeWorldMatrix = function (force) {
  19136. if (this._isWorldMatrixFrozen) {
  19137. return this._worldMatrix;
  19138. }
  19139. if (!force && this.isSynchronized(true)) {
  19140. this._currentRenderId = this.getScene().getRenderId();
  19141. return this._worldMatrix;
  19142. }
  19143. this._cache.position.copyFrom(this.position);
  19144. this._cache.scaling.copyFrom(this.scaling);
  19145. this._cache.pivotMatrixUpdated = false;
  19146. this._cache.billboardMode = this.billboardMode;
  19147. this._currentRenderId = this.getScene().getRenderId();
  19148. this._childRenderId = this.getScene().getRenderId();
  19149. this._isDirty = false;
  19150. // Scaling
  19151. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19152. // Rotation
  19153. //rotate, if quaternion is set and rotation was used
  19154. if (this.rotationQuaternion) {
  19155. var len = this.rotation.length();
  19156. if (len) {
  19157. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19158. this.rotation.copyFromFloats(0, 0, 0);
  19159. }
  19160. }
  19161. if (this.rotationQuaternion) {
  19162. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19163. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19164. }
  19165. else {
  19166. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19167. this._cache.rotation.copyFrom(this.rotation);
  19168. }
  19169. // Translation
  19170. var camera = this.getScene().activeCamera;
  19171. if (this.infiniteDistance && !this.parent && camera) {
  19172. var cameraWorldMatrix = camera.getWorldMatrix();
  19173. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19174. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19175. }
  19176. else {
  19177. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19178. }
  19179. // Composing transformations
  19180. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19181. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19182. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19183. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19184. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19185. // Need to decompose each rotation here
  19186. var currentPosition = BABYLON.Tmp.Vector3[3];
  19187. if (this.parent && this.parent.getWorldMatrix) {
  19188. if (this._transformToBoneReferal) {
  19189. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19190. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19191. }
  19192. else {
  19193. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19194. }
  19195. }
  19196. else {
  19197. currentPosition.copyFrom(this.position);
  19198. }
  19199. currentPosition.subtractInPlace(camera.globalPosition);
  19200. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19201. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19202. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19203. }
  19204. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19205. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19206. }
  19207. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19208. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19209. }
  19210. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19211. }
  19212. else {
  19213. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19214. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19215. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19216. }
  19217. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19218. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19219. }
  19220. // Local world
  19221. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19222. // Parent
  19223. if (this.parent && this.parent.getWorldMatrix) {
  19224. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19225. if (this._transformToBoneReferal) {
  19226. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19227. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19228. }
  19229. else {
  19230. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19231. }
  19232. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19233. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19234. this._worldMatrix.copyFrom(this._localWorld);
  19235. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19236. }
  19237. else {
  19238. if (this._transformToBoneReferal) {
  19239. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19240. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19241. }
  19242. else {
  19243. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19244. }
  19245. }
  19246. this._markSyncedWithParent();
  19247. }
  19248. else {
  19249. this._worldMatrix.copyFrom(this._localWorld);
  19250. }
  19251. // Post multiply inverse of pivotMatrix
  19252. if (this._postMultiplyPivotMatrix) {
  19253. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19254. }
  19255. // Normal matrix
  19256. if (!this.ignoreNonUniformScaling) {
  19257. if (this.scaling.isNonUniform) {
  19258. this._updateNonUniformScalingState(true);
  19259. }
  19260. else if (this.parent && this.parent._nonUniformScaling) {
  19261. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19262. }
  19263. else {
  19264. this._updateNonUniformScalingState(false);
  19265. }
  19266. }
  19267. else {
  19268. this._updateNonUniformScalingState(false);
  19269. }
  19270. this._afterComputeWorldMatrix();
  19271. // Absolute position
  19272. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19273. // Callbacks
  19274. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19275. if (!this._poseMatrix) {
  19276. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19277. }
  19278. // Cache the determinant
  19279. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19280. return this._worldMatrix;
  19281. };
  19282. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19283. };
  19284. /**
  19285. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19286. * @param func: callback function to add
  19287. *
  19288. * Returns the TransformNode.
  19289. */
  19290. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19291. this.onAfterWorldMatrixUpdateObservable.add(func);
  19292. return this;
  19293. };
  19294. /**
  19295. * Removes a registered callback function.
  19296. * Returns the TransformNode.
  19297. */
  19298. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19299. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19300. return this;
  19301. };
  19302. /**
  19303. * Clone the current transform node
  19304. * Returns the new transform node
  19305. * @param name Name of the new clone
  19306. * @param newParent New parent for the clone
  19307. * @param doNotCloneChildren Do not clone children hierarchy
  19308. */
  19309. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19310. var _this = this;
  19311. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19312. result.name = name;
  19313. result.id = name;
  19314. if (newParent) {
  19315. result.parent = newParent;
  19316. }
  19317. if (!doNotCloneChildren) {
  19318. // Children
  19319. var directDescendants = this.getDescendants(true);
  19320. for (var index = 0; index < directDescendants.length; index++) {
  19321. var child = directDescendants[index];
  19322. if (child.clone) {
  19323. child.clone(name + "." + child.name, result);
  19324. }
  19325. }
  19326. }
  19327. return result;
  19328. };
  19329. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19330. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19331. serializationObject.type = this.getClassName();
  19332. // Parent
  19333. if (this.parent) {
  19334. serializationObject.parentId = this.parent.id;
  19335. }
  19336. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19337. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19338. }
  19339. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19340. serializationObject.isEnabled = this.isEnabled();
  19341. // Parent
  19342. if (this.parent) {
  19343. serializationObject.parentId = this.parent.id;
  19344. }
  19345. return serializationObject;
  19346. };
  19347. // Statics
  19348. /**
  19349. * Returns a new TransformNode object parsed from the source provided.
  19350. * The parameter `parsedMesh` is the source.
  19351. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19352. */
  19353. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19354. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19355. if (BABYLON.Tags) {
  19356. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19357. }
  19358. if (parsedTransformNode.localMatrix) {
  19359. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19360. }
  19361. else if (parsedTransformNode.pivotMatrix) {
  19362. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19363. }
  19364. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19365. // Parent
  19366. if (parsedTransformNode.parentId) {
  19367. transformNode._waitingParentId = parsedTransformNode.parentId;
  19368. }
  19369. return transformNode;
  19370. };
  19371. /**
  19372. * Releases resources associated with this transform node.
  19373. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19374. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19375. */
  19376. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19377. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19378. // Animations
  19379. this.getScene().stopAnimation(this);
  19380. // Remove from scene
  19381. this.getScene().removeTransformNode(this);
  19382. this.onAfterWorldMatrixUpdateObservable.clear();
  19383. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19384. };
  19385. // Statics
  19386. TransformNode.BILLBOARDMODE_NONE = 0;
  19387. TransformNode.BILLBOARDMODE_X = 1;
  19388. TransformNode.BILLBOARDMODE_Y = 2;
  19389. TransformNode.BILLBOARDMODE_Z = 4;
  19390. TransformNode.BILLBOARDMODE_ALL = 7;
  19391. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19392. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19393. __decorate([
  19394. BABYLON.serializeAsVector3()
  19395. ], TransformNode.prototype, "_rotation", void 0);
  19396. __decorate([
  19397. BABYLON.serializeAsQuaternion()
  19398. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19399. __decorate([
  19400. BABYLON.serializeAsVector3()
  19401. ], TransformNode.prototype, "_scaling", void 0);
  19402. __decorate([
  19403. BABYLON.serialize()
  19404. ], TransformNode.prototype, "billboardMode", void 0);
  19405. __decorate([
  19406. BABYLON.serialize()
  19407. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19408. __decorate([
  19409. BABYLON.serialize()
  19410. ], TransformNode.prototype, "infiniteDistance", void 0);
  19411. __decorate([
  19412. BABYLON.serialize()
  19413. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19414. __decorate([
  19415. BABYLON.serializeAsVector3()
  19416. ], TransformNode.prototype, "position", void 0);
  19417. return TransformNode;
  19418. }(BABYLON.Node));
  19419. BABYLON.TransformNode = TransformNode;
  19420. })(BABYLON || (BABYLON = {}));
  19421. //# sourceMappingURL=babylon.transformNode.js.map
  19422. var BABYLON;
  19423. (function (BABYLON) {
  19424. /**
  19425. * Class used to store all common mesh properties
  19426. */
  19427. var AbstractMesh = /** @class */ (function (_super) {
  19428. __extends(AbstractMesh, _super);
  19429. // Constructor
  19430. /**
  19431. * Creates a new AbstractMesh
  19432. * @param name defines the name of the mesh
  19433. * @param scene defines the hosting scene
  19434. */
  19435. function AbstractMesh(name, scene) {
  19436. if (scene === void 0) { scene = null; }
  19437. var _this = _super.call(this, name, scene, false) || this;
  19438. _this._facetNb = 0; // facet number
  19439. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19440. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19441. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19442. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19443. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19444. _this._subDiv = {
  19445. max: 1,
  19446. X: 1,
  19447. Y: 1,
  19448. Z: 1
  19449. };
  19450. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19451. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19452. // Events
  19453. /**
  19454. * An event triggered when this mesh collides with another one
  19455. */
  19456. _this.onCollideObservable = new BABYLON.Observable();
  19457. /**
  19458. * An event triggered when the collision's position changes
  19459. */
  19460. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19461. /**
  19462. * An event triggered when material is changed
  19463. */
  19464. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19465. // Properties
  19466. /**
  19467. * Gets or sets the orientation for POV movement & rotation
  19468. */
  19469. _this.definedFacingForward = true;
  19470. /**
  19471. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19472. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19473. * * 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.
  19474. * @see http://doc.babylonjs.com/features/occlusionquery
  19475. */
  19476. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19477. /**
  19478. * 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:
  19479. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19480. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19481. * * 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.
  19482. * @see http://doc.babylonjs.com/features/occlusionquery
  19483. */
  19484. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19485. /**
  19486. * 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.
  19487. * The default value is -1 which means don't break the query and wait till the result
  19488. * @see http://doc.babylonjs.com/features/occlusionquery
  19489. */
  19490. _this.occlusionRetryCount = -1;
  19491. _this._occlusionInternalRetryCounter = 0;
  19492. _this._isOccluded = false;
  19493. _this._isOcclusionQueryInProgress = false;
  19494. _this._visibility = 1.0;
  19495. /** Gets or sets the alpha index used to sort transparent meshes
  19496. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19497. */
  19498. _this.alphaIndex = Number.MAX_VALUE;
  19499. /**
  19500. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19501. */
  19502. _this.isVisible = true;
  19503. /**
  19504. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19505. */
  19506. _this.isPickable = true;
  19507. /**
  19508. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19509. */
  19510. _this.showBoundingBox = false;
  19511. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19512. _this.showSubMeshesBoundingBox = false;
  19513. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19514. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19515. */
  19516. _this.isBlocker = false;
  19517. /**
  19518. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19519. */
  19520. _this.enablePointerMoveEvents = false;
  19521. /**
  19522. * Specifies the rendering group id for this mesh (0 by default)
  19523. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19524. */
  19525. _this.renderingGroupId = 0;
  19526. _this._receiveShadows = false;
  19527. /**
  19528. * Gets or sets a boolean indicating if the outline must be rendered as well
  19529. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19530. */
  19531. _this.renderOutline = false;
  19532. /** Defines color to use when rendering outline */
  19533. _this.outlineColor = BABYLON.Color3.Red();
  19534. /** Define width to use when rendering outline */
  19535. _this.outlineWidth = 0.02;
  19536. /**
  19537. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19538. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19539. */
  19540. _this.renderOverlay = false;
  19541. /** Defines color to use when rendering overlay */
  19542. _this.overlayColor = BABYLON.Color3.Red();
  19543. /** Defines alpha to use when rendering overlay */
  19544. _this.overlayAlpha = 0.5;
  19545. _this._hasVertexAlpha = false;
  19546. _this._useVertexColors = true;
  19547. _this._computeBonesUsingShaders = true;
  19548. _this._numBoneInfluencers = 4;
  19549. _this._applyFog = true;
  19550. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19551. _this.useOctreeForRenderingSelection = true;
  19552. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19553. _this.useOctreeForPicking = true;
  19554. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19555. _this.useOctreeForCollisions = true;
  19556. _this._layerMask = 0x0FFFFFFF;
  19557. /**
  19558. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19559. */
  19560. _this.alwaysSelectAsActiveMesh = false;
  19561. /**
  19562. * Gets or sets the current action manager
  19563. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19564. */
  19565. _this.actionManager = null;
  19566. /**
  19567. * Gets or sets impostor used for physic simulation
  19568. * @see http://doc.babylonjs.com/features/physics_engine
  19569. */
  19570. _this.physicsImpostor = null;
  19571. // Collisions
  19572. _this._checkCollisions = false;
  19573. _this._collisionMask = -1;
  19574. _this._collisionGroup = -1;
  19575. /**
  19576. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19577. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19578. */
  19579. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19580. /**
  19581. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19582. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19583. */
  19584. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19585. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19586. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19587. // Edges
  19588. /**
  19589. * Defines edge width used when edgesRenderer is enabled
  19590. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19591. */
  19592. _this.edgesWidth = 1;
  19593. /**
  19594. * Defines edge color used when edgesRenderer is enabled
  19595. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19596. */
  19597. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19598. // Cache
  19599. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19600. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19601. /** @hidden */
  19602. _this._renderId = 0;
  19603. /** @hidden */
  19604. _this._intersectionsInProgress = new Array();
  19605. /** @hidden */
  19606. _this._unIndexed = false;
  19607. /** @hidden */
  19608. _this._lightSources = new Array();
  19609. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19610. if (collidedMesh === void 0) { collidedMesh = null; }
  19611. //TODO move this to the collision coordinator!
  19612. if (_this.getScene().workerCollisions)
  19613. newPosition.multiplyInPlace(_this._collider._radius);
  19614. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19615. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19616. _this.position.addInPlace(_this._diffPositionForCollisions);
  19617. }
  19618. if (collidedMesh) {
  19619. _this.onCollideObservable.notifyObservers(collidedMesh);
  19620. }
  19621. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19622. };
  19623. _this.getScene().addMesh(_this);
  19624. _this._resyncLightSources();
  19625. return _this;
  19626. }
  19627. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19628. /**
  19629. * No billboard
  19630. */
  19631. get: function () {
  19632. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19633. },
  19634. enumerable: true,
  19635. configurable: true
  19636. });
  19637. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19638. /** Billboard on X axis */
  19639. get: function () {
  19640. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19641. },
  19642. enumerable: true,
  19643. configurable: true
  19644. });
  19645. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19646. /** Billboard on Y axis */
  19647. get: function () {
  19648. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19654. /** Billboard on Z axis */
  19655. get: function () {
  19656. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19662. /** Billboard on all axes */
  19663. get: function () {
  19664. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19670. /**
  19671. * Gets the number of facets in the mesh
  19672. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19673. */
  19674. get: function () {
  19675. return this._facetNb;
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19681. /**
  19682. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19683. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19684. */
  19685. get: function () {
  19686. return this._partitioningSubdivisions;
  19687. },
  19688. set: function (nb) {
  19689. this._partitioningSubdivisions = nb;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19695. /**
  19696. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19697. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19698. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19699. */
  19700. get: function () {
  19701. return this._partitioningBBoxRatio;
  19702. },
  19703. set: function (ratio) {
  19704. this._partitioningBBoxRatio = ratio;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19710. /**
  19711. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19712. * Works only for updatable meshes.
  19713. * Doesn't work with multi-materials
  19714. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19715. */
  19716. get: function () {
  19717. return this._facetDepthSort;
  19718. },
  19719. set: function (sort) {
  19720. this._facetDepthSort = sort;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19726. /**
  19727. * The location (Vector3) where the facet depth sort must be computed from.
  19728. * By default, the active camera position.
  19729. * Used only when facet depth sort is enabled
  19730. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19731. */
  19732. get: function () {
  19733. return this._facetDepthSortFrom;
  19734. },
  19735. set: function (location) {
  19736. this._facetDepthSortFrom = location;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19742. /**
  19743. * gets a boolean indicating if facetData is enabled
  19744. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19745. */
  19746. get: function () {
  19747. return this._facetDataEnabled;
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. /** @hidden */
  19753. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19754. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19755. return false;
  19756. }
  19757. this._markSubMeshesAsMiscDirty();
  19758. return true;
  19759. };
  19760. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19761. /** Set a function to call when this mesh collides with another one */
  19762. set: function (callback) {
  19763. if (this._onCollideObserver) {
  19764. this.onCollideObservable.remove(this._onCollideObserver);
  19765. }
  19766. this._onCollideObserver = this.onCollideObservable.add(callback);
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19772. /** Set a function to call when the collision's position changes */
  19773. set: function (callback) {
  19774. if (this._onCollisionPositionChangeObserver) {
  19775. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19776. }
  19777. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19783. /**
  19784. * 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
  19785. * @see http://doc.babylonjs.com/features/occlusionquery
  19786. */
  19787. get: function () {
  19788. return this._isOccluded;
  19789. },
  19790. set: function (value) {
  19791. this._isOccluded = value;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19797. /**
  19798. * Flag to check the progress status of the query
  19799. * @see http://doc.babylonjs.com/features/occlusionquery
  19800. */
  19801. get: function () {
  19802. return this._isOcclusionQueryInProgress;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19808. /**
  19809. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19810. */
  19811. get: function () {
  19812. return this._visibility;
  19813. },
  19814. /**
  19815. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19816. */
  19817. set: function (value) {
  19818. if (this._visibility === value) {
  19819. return;
  19820. }
  19821. this._visibility = value;
  19822. this._markSubMeshesAsMiscDirty();
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(AbstractMesh.prototype, "material", {
  19828. /** Gets or sets current material */
  19829. get: function () {
  19830. return this._material;
  19831. },
  19832. set: function (value) {
  19833. if (this._material === value) {
  19834. return;
  19835. }
  19836. this._material = value;
  19837. if (this.onMaterialChangedObservable.hasObservers) {
  19838. this.onMaterialChangedObservable.notifyObservers(this);
  19839. }
  19840. if (!this.subMeshes) {
  19841. return;
  19842. }
  19843. this._unBindEffect();
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19849. /**
  19850. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19851. * @see http://doc.babylonjs.com/babylon101/shadows
  19852. */
  19853. get: function () {
  19854. return this._receiveShadows;
  19855. },
  19856. set: function (value) {
  19857. if (this._receiveShadows === value) {
  19858. return;
  19859. }
  19860. this._receiveShadows = value;
  19861. this._markSubMeshesAsLightDirty();
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19867. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19868. get: function () {
  19869. return this._hasVertexAlpha;
  19870. },
  19871. set: function (value) {
  19872. if (this._hasVertexAlpha === value) {
  19873. return;
  19874. }
  19875. this._hasVertexAlpha = value;
  19876. this._markSubMeshesAsAttributesDirty();
  19877. this._markSubMeshesAsMiscDirty();
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19883. /** 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) */
  19884. get: function () {
  19885. return this._useVertexColors;
  19886. },
  19887. set: function (value) {
  19888. if (this._useVertexColors === value) {
  19889. return;
  19890. }
  19891. this._useVertexColors = value;
  19892. this._markSubMeshesAsAttributesDirty();
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19898. /**
  19899. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19900. */
  19901. get: function () {
  19902. return this._computeBonesUsingShaders;
  19903. },
  19904. set: function (value) {
  19905. if (this._computeBonesUsingShaders === value) {
  19906. return;
  19907. }
  19908. this._computeBonesUsingShaders = value;
  19909. this._markSubMeshesAsAttributesDirty();
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19915. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19916. get: function () {
  19917. return this._numBoneInfluencers;
  19918. },
  19919. set: function (value) {
  19920. if (this._numBoneInfluencers === value) {
  19921. return;
  19922. }
  19923. this._numBoneInfluencers = value;
  19924. this._markSubMeshesAsAttributesDirty();
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19930. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19931. get: function () {
  19932. return this._applyFog;
  19933. },
  19934. set: function (value) {
  19935. if (this._applyFog === value) {
  19936. return;
  19937. }
  19938. this._applyFog = value;
  19939. this._markSubMeshesAsMiscDirty();
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19945. /**
  19946. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19947. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19948. */
  19949. get: function () {
  19950. return this._layerMask;
  19951. },
  19952. set: function (value) {
  19953. if (value === this._layerMask) {
  19954. return;
  19955. }
  19956. this._layerMask = value;
  19957. this._resyncLightSources();
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19963. /**
  19964. * Gets or sets a collision mask used to mask collisions (default is -1).
  19965. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19966. */
  19967. get: function () {
  19968. return this._collisionMask;
  19969. },
  19970. set: function (mask) {
  19971. this._collisionMask = !isNaN(mask) ? mask : -1;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19977. /**
  19978. * Gets or sets the current collision group mask (-1 by default).
  19979. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19980. */
  19981. get: function () {
  19982. return this._collisionGroup;
  19983. },
  19984. set: function (mask) {
  19985. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19991. /** @hidden */
  19992. get: function () {
  19993. return null;
  19994. },
  19995. enumerable: true,
  19996. configurable: true
  19997. });
  19998. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19999. get: function () {
  20000. return this._skeleton;
  20001. },
  20002. /**
  20003. * Gets or sets a skeleton to apply skining transformations
  20004. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20005. */
  20006. set: function (value) {
  20007. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20008. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20009. }
  20010. if (value && value.needInitialSkinMatrix) {
  20011. value._registerMeshWithPoseMatrix(this);
  20012. }
  20013. this._skeleton = value;
  20014. if (!this._skeleton) {
  20015. this._bonesTransformMatrices = null;
  20016. }
  20017. this._markSubMeshesAsAttributesDirty();
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. /**
  20023. * Returns the string "AbstractMesh"
  20024. * @returns "AbstractMesh"
  20025. */
  20026. AbstractMesh.prototype.getClassName = function () {
  20027. return "AbstractMesh";
  20028. };
  20029. /**
  20030. * Gets a string representation of the current mesh
  20031. * @param fullDetails defines a boolean indicating if full details must be included
  20032. * @returns a string representation of the current mesh
  20033. */
  20034. AbstractMesh.prototype.toString = function (fullDetails) {
  20035. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20036. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20037. if (this._skeleton) {
  20038. ret += ", skeleton: " + this._skeleton.name;
  20039. }
  20040. if (fullDetails) {
  20041. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20042. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20043. }
  20044. return ret;
  20045. };
  20046. /** @hidden */
  20047. AbstractMesh.prototype._rebuild = function () {
  20048. if (this._occlusionQuery) {
  20049. this._occlusionQuery = null;
  20050. }
  20051. if (this._edgesRenderer) {
  20052. this._edgesRenderer._rebuild();
  20053. }
  20054. if (!this.subMeshes) {
  20055. return;
  20056. }
  20057. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20058. var subMesh = _a[_i];
  20059. subMesh._rebuild();
  20060. }
  20061. };
  20062. /** @hidden */
  20063. AbstractMesh.prototype._resyncLightSources = function () {
  20064. this._lightSources.length = 0;
  20065. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20066. var light = _a[_i];
  20067. if (!light.isEnabled()) {
  20068. continue;
  20069. }
  20070. if (light.canAffectMesh(this)) {
  20071. this._lightSources.push(light);
  20072. }
  20073. }
  20074. this._markSubMeshesAsLightDirty();
  20075. };
  20076. /** @hidden */
  20077. AbstractMesh.prototype._resyncLighSource = function (light) {
  20078. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20079. var index = this._lightSources.indexOf(light);
  20080. if (index === -1) {
  20081. if (!isIn) {
  20082. return;
  20083. }
  20084. this._lightSources.push(light);
  20085. }
  20086. else {
  20087. if (isIn) {
  20088. return;
  20089. }
  20090. this._lightSources.splice(index, 1);
  20091. }
  20092. this._markSubMeshesAsLightDirty();
  20093. };
  20094. /** @hidden */
  20095. AbstractMesh.prototype._unBindEffect = function () {
  20096. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20097. var subMesh = _a[_i];
  20098. subMesh.setEffect(null);
  20099. }
  20100. };
  20101. /** @hidden */
  20102. AbstractMesh.prototype._removeLightSource = function (light) {
  20103. var index = this._lightSources.indexOf(light);
  20104. if (index === -1) {
  20105. return;
  20106. }
  20107. this._lightSources.splice(index, 1);
  20108. this._markSubMeshesAsLightDirty();
  20109. };
  20110. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20111. if (!this.subMeshes) {
  20112. return;
  20113. }
  20114. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20115. var subMesh = _a[_i];
  20116. if (subMesh._materialDefines) {
  20117. func(subMesh._materialDefines);
  20118. }
  20119. }
  20120. };
  20121. /** @hidden */
  20122. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20123. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20124. };
  20125. /** @hidden */
  20126. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20127. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20128. };
  20129. /** @hidden */
  20130. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20131. if (!this.subMeshes) {
  20132. return;
  20133. }
  20134. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20135. var subMesh = _a[_i];
  20136. var material = subMesh.getMaterial();
  20137. if (material) {
  20138. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20139. }
  20140. }
  20141. };
  20142. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20143. /**
  20144. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20145. */
  20146. get: function () {
  20147. return this._scaling;
  20148. },
  20149. set: function (newScaling) {
  20150. this._scaling = newScaling;
  20151. if (this.physicsImpostor) {
  20152. this.physicsImpostor.forceUpdate();
  20153. }
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. // Methods
  20159. /**
  20160. * Disables the mesh edge rendering mode
  20161. * @returns the currentAbstractMesh
  20162. */
  20163. AbstractMesh.prototype.disableEdgesRendering = function () {
  20164. if (this._edgesRenderer) {
  20165. this._edgesRenderer.dispose();
  20166. this._edgesRenderer = null;
  20167. }
  20168. return this;
  20169. };
  20170. /**
  20171. * Enables the edge rendering mode on the mesh.
  20172. * This mode makes the mesh edges visible
  20173. * @param epsilon defines the maximal distance between two angles to detect a face
  20174. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20175. * @returns the currentAbstractMesh
  20176. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20177. */
  20178. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20179. if (epsilon === void 0) { epsilon = 0.95; }
  20180. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20181. this.disableEdgesRendering();
  20182. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20183. return this;
  20184. };
  20185. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20186. /**
  20187. * Gets the edgesRenderer associated with the mesh
  20188. */
  20189. get: function () {
  20190. return this._edgesRenderer;
  20191. },
  20192. enumerable: true,
  20193. configurable: true
  20194. });
  20195. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20196. /**
  20197. * Returns true if the mesh is blocked. Implemented by child classes
  20198. */
  20199. get: function () {
  20200. return false;
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. /**
  20206. * Returns the mesh itself by default. Implemented by child classes
  20207. * @param camera defines the camera to use to pick the right LOD level
  20208. * @returns the currentAbstractMesh
  20209. */
  20210. AbstractMesh.prototype.getLOD = function (camera) {
  20211. return this;
  20212. };
  20213. /**
  20214. * Returns 0 by default. Implemented by child classes
  20215. * @returns an integer
  20216. */
  20217. AbstractMesh.prototype.getTotalVertices = function () {
  20218. return 0;
  20219. };
  20220. /**
  20221. * Returns null by default. Implemented by child classes
  20222. * @returns null
  20223. */
  20224. AbstractMesh.prototype.getIndices = function () {
  20225. return null;
  20226. };
  20227. /**
  20228. * Returns the array of the requested vertex data kind. Implemented by child classes
  20229. * @param kind defines the vertex data kind to use
  20230. * @returns null
  20231. */
  20232. AbstractMesh.prototype.getVerticesData = function (kind) {
  20233. return null;
  20234. };
  20235. /**
  20236. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20237. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20238. * Note that a new underlying VertexBuffer object is created each call.
  20239. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20240. * @param kind defines vertex data kind:
  20241. * * BABYLON.VertexBuffer.PositionKind
  20242. * * BABYLON.VertexBuffer.UVKind
  20243. * * BABYLON.VertexBuffer.UV2Kind
  20244. * * BABYLON.VertexBuffer.UV3Kind
  20245. * * BABYLON.VertexBuffer.UV4Kind
  20246. * * BABYLON.VertexBuffer.UV5Kind
  20247. * * BABYLON.VertexBuffer.UV6Kind
  20248. * * BABYLON.VertexBuffer.ColorKind
  20249. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20250. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20251. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20252. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20253. * @param data defines the data source
  20254. * @param updatable defines if the data must be flagged as updatable (or static)
  20255. * @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
  20256. * @returns the current mesh
  20257. */
  20258. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20259. return this;
  20260. };
  20261. /**
  20262. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20263. * If the mesh has no geometry, it is simply returned as it is.
  20264. * @param kind defines vertex data kind:
  20265. * * BABYLON.VertexBuffer.PositionKind
  20266. * * BABYLON.VertexBuffer.UVKind
  20267. * * BABYLON.VertexBuffer.UV2Kind
  20268. * * BABYLON.VertexBuffer.UV3Kind
  20269. * * BABYLON.VertexBuffer.UV4Kind
  20270. * * BABYLON.VertexBuffer.UV5Kind
  20271. * * BABYLON.VertexBuffer.UV6Kind
  20272. * * BABYLON.VertexBuffer.ColorKind
  20273. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20274. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20275. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20276. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20277. * @param data defines the data source
  20278. * @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
  20279. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20280. * @returns the current mesh
  20281. */
  20282. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20283. return this;
  20284. };
  20285. /**
  20286. * Sets the mesh indices,
  20287. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20288. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20289. * @param totalVertices Defines the total number of vertices
  20290. * @returns the current mesh
  20291. */
  20292. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20293. return this;
  20294. };
  20295. /**
  20296. * Gets a boolean indicating if specific vertex data is present
  20297. * @param kind defines the vertex data kind to use
  20298. * @returns true is data kind is present
  20299. */
  20300. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20301. return false;
  20302. };
  20303. /**
  20304. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20305. * @returns a BoundingInfo
  20306. */
  20307. AbstractMesh.prototype.getBoundingInfo = function () {
  20308. if (this._masterMesh) {
  20309. return this._masterMesh.getBoundingInfo();
  20310. }
  20311. if (!this._boundingInfo) {
  20312. // this._boundingInfo is being created here
  20313. this._updateBoundingInfo();
  20314. }
  20315. // cannot be null.
  20316. return this._boundingInfo;
  20317. };
  20318. /**
  20319. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20320. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20321. * @returns the current mesh
  20322. */
  20323. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20324. if (includeDescendants === void 0) { includeDescendants = true; }
  20325. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20326. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20327. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20328. if (maxDimension === 0) {
  20329. return this;
  20330. }
  20331. var scale = 1 / maxDimension;
  20332. this.scaling.scaleInPlace(scale);
  20333. return this;
  20334. };
  20335. /**
  20336. * Overwrite the current bounding info
  20337. * @param boundingInfo defines the new bounding info
  20338. * @returns the current mesh
  20339. */
  20340. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20341. this._boundingInfo = boundingInfo;
  20342. return this;
  20343. };
  20344. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20345. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20346. get: function () {
  20347. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20348. },
  20349. enumerable: true,
  20350. configurable: true
  20351. });
  20352. /** @hidden */
  20353. AbstractMesh.prototype._preActivate = function () {
  20354. };
  20355. /** @hidden */
  20356. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20357. };
  20358. /** @hidden */
  20359. AbstractMesh.prototype._activate = function (renderId) {
  20360. this._renderId = renderId;
  20361. };
  20362. /**
  20363. * Gets the current world matrix
  20364. * @returns a Matrix
  20365. */
  20366. AbstractMesh.prototype.getWorldMatrix = function () {
  20367. if (this._masterMesh) {
  20368. return this._masterMesh.getWorldMatrix();
  20369. }
  20370. return _super.prototype.getWorldMatrix.call(this);
  20371. };
  20372. /** @hidden */
  20373. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20374. if (this._masterMesh) {
  20375. return this._masterMesh._getWorldMatrixDeterminant();
  20376. }
  20377. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20378. };
  20379. // ================================== Point of View Movement =================================
  20380. /**
  20381. * Perform relative position change from the point of view of behind the front of the mesh.
  20382. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20383. * Supports definition of mesh facing forward or backward
  20384. * @param amountRight defines the distance on the right axis
  20385. * @param amountUp defines the distance on the up axis
  20386. * @param amountForward defines the distance on the forward axis
  20387. * @returns the current mesh
  20388. */
  20389. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20390. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20391. return this;
  20392. };
  20393. /**
  20394. * Calculate relative position change from the point of view of behind the front of the mesh.
  20395. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20396. * Supports definition of mesh facing forward or backward
  20397. * @param amountRight defines the distance on the right axis
  20398. * @param amountUp defines the distance on the up axis
  20399. * @param amountForward defines the distance on the forward axis
  20400. * @returns the new displacement vector
  20401. */
  20402. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20403. var rotMatrix = new BABYLON.Matrix();
  20404. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20405. rotQuaternion.toRotationMatrix(rotMatrix);
  20406. var translationDelta = BABYLON.Vector3.Zero();
  20407. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20408. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20409. return translationDelta;
  20410. };
  20411. // ================================== Point of View Rotation =================================
  20412. /**
  20413. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20414. * Supports definition of mesh facing forward or backward
  20415. * @param flipBack defines the flip
  20416. * @param twirlClockwise defines the twirl
  20417. * @param tiltRight defines the tilt
  20418. * @returns the current mesh
  20419. */
  20420. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20421. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20422. return this;
  20423. };
  20424. /**
  20425. * Calculate 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 new rotation vector
  20431. */
  20432. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20433. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20434. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20435. };
  20436. /**
  20437. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20438. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20439. * @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
  20440. * @returns the new bounding vectors
  20441. */
  20442. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20443. if (includeDescendants === void 0) { includeDescendants = true; }
  20444. if (predicate === void 0) { predicate = null; }
  20445. // Ensures that all world matrix will be recomputed.
  20446. this.getScene().incrementRenderId();
  20447. this.computeWorldMatrix(true);
  20448. var min;
  20449. var max;
  20450. var boundingInfo = this.getBoundingInfo();
  20451. if (!this.subMeshes) {
  20452. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20453. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20454. }
  20455. else {
  20456. min = boundingInfo.boundingBox.minimumWorld;
  20457. max = boundingInfo.boundingBox.maximumWorld;
  20458. }
  20459. if (includeDescendants) {
  20460. var descendants = this.getDescendants(false);
  20461. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20462. var descendant = descendants_1[_i];
  20463. var childMesh = descendant;
  20464. childMesh.computeWorldMatrix(true);
  20465. // Filters meshes based on custom predicate function.
  20466. if (predicate && !predicate(childMesh)) {
  20467. continue;
  20468. }
  20469. //make sure we have the needed params to get mix and max
  20470. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20471. continue;
  20472. }
  20473. var childBoundingInfo = childMesh.getBoundingInfo();
  20474. var boundingBox = childBoundingInfo.boundingBox;
  20475. var minBox = boundingBox.minimumWorld;
  20476. var maxBox = boundingBox.maximumWorld;
  20477. BABYLON.Tools.CheckExtends(minBox, min, max);
  20478. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20479. }
  20480. }
  20481. return {
  20482. min: min,
  20483. max: max
  20484. };
  20485. };
  20486. /** @hidden */
  20487. AbstractMesh.prototype._updateBoundingInfo = function () {
  20488. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20489. this._boundingInfo.update(this.worldMatrixFromCache);
  20490. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20491. return this;
  20492. };
  20493. /** @hidden */
  20494. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20495. if (!this.subMeshes) {
  20496. return this;
  20497. }
  20498. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20499. var subMesh = this.subMeshes[subIndex];
  20500. if (!subMesh.IsGlobal) {
  20501. subMesh.updateBoundingInfo(matrix);
  20502. }
  20503. }
  20504. return this;
  20505. };
  20506. /** @hidden */
  20507. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20508. // Bounding info
  20509. this._updateBoundingInfo();
  20510. };
  20511. /**
  20512. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20513. * A mesh is in the frustum if its bounding box intersects the frustum
  20514. * @param frustumPlanes defines the frustum to test
  20515. * @returns true if the mesh is in the frustum planes
  20516. */
  20517. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20518. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20519. };
  20520. /**
  20521. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20522. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20523. * @param frustumPlanes defines the frustum to test
  20524. * @returns true if the mesh is completely in the frustum planes
  20525. */
  20526. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20527. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20528. };
  20529. /**
  20530. * True if the mesh intersects another mesh or a SolidParticle object
  20531. * @param mesh defines a target mesh or SolidParticle to test
  20532. * @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)
  20533. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20534. * @returns true if there is an intersection
  20535. */
  20536. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20537. if (precise === void 0) { precise = false; }
  20538. if (!this._boundingInfo || !mesh._boundingInfo) {
  20539. return false;
  20540. }
  20541. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20542. return true;
  20543. }
  20544. if (includeDescendants) {
  20545. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20546. var child = _a[_i];
  20547. if (child.intersectsMesh(mesh, precise, true)) {
  20548. return true;
  20549. }
  20550. }
  20551. }
  20552. return false;
  20553. };
  20554. /**
  20555. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20556. * @param point defines the point to test
  20557. * @returns true if there is an intersection
  20558. */
  20559. AbstractMesh.prototype.intersectsPoint = function (point) {
  20560. if (!this._boundingInfo) {
  20561. return false;
  20562. }
  20563. return this._boundingInfo.intersectsPoint(point);
  20564. };
  20565. /**
  20566. * Gets the current physics impostor
  20567. * @see http://doc.babylonjs.com/features/physics_engine
  20568. * @returns a physics impostor or null
  20569. */
  20570. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20571. return this.physicsImpostor;
  20572. };
  20573. /**
  20574. * Gets the position of the current mesh in camera space
  20575. * @param camera defines the camera to use
  20576. * @returns a position
  20577. */
  20578. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20579. if (camera === void 0) { camera = null; }
  20580. if (!camera) {
  20581. camera = this.getScene().activeCamera;
  20582. }
  20583. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20584. };
  20585. /**
  20586. * Returns the distance from the mesh to the active camera
  20587. * @param camera defines the camera to use
  20588. * @returns the distance
  20589. */
  20590. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20591. if (camera === void 0) { camera = null; }
  20592. if (!camera) {
  20593. camera = this.getScene().activeCamera;
  20594. }
  20595. return this.absolutePosition.subtract(camera.position).length();
  20596. };
  20597. /**
  20598. * Apply a physic impulse to the mesh
  20599. * @param force defines the force to apply
  20600. * @param contactPoint defines where to apply the force
  20601. * @returns the current mesh
  20602. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20603. */
  20604. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20605. if (!this.physicsImpostor) {
  20606. return this;
  20607. }
  20608. this.physicsImpostor.applyImpulse(force, contactPoint);
  20609. return this;
  20610. };
  20611. /**
  20612. * Creates a physic joint between two meshes
  20613. * @param otherMesh defines the other mesh to use
  20614. * @param pivot1 defines the pivot to use on this mesh
  20615. * @param pivot2 defines the pivot to use on the other mesh
  20616. * @param options defines additional options (can be plugin dependent)
  20617. * @returns the current mesh
  20618. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20619. */
  20620. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20621. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20622. return this;
  20623. }
  20624. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20625. mainPivot: pivot1,
  20626. connectedPivot: pivot2,
  20627. nativeParams: options
  20628. });
  20629. return this;
  20630. };
  20631. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20632. // Collisions
  20633. /**
  20634. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20635. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20636. */
  20637. get: function () {
  20638. return this._checkCollisions;
  20639. },
  20640. set: function (collisionEnabled) {
  20641. this._checkCollisions = collisionEnabled;
  20642. if (this.getScene().workerCollisions) {
  20643. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20644. }
  20645. },
  20646. enumerable: true,
  20647. configurable: true
  20648. });
  20649. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20650. /**
  20651. * Gets Collider object used to compute collisions (not physics)
  20652. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20653. */
  20654. get: function () {
  20655. return this._collider;
  20656. },
  20657. enumerable: true,
  20658. configurable: true
  20659. });
  20660. /**
  20661. * Move the mesh using collision engine
  20662. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20663. * @param displacement defines the requested displacement vector
  20664. * @returns the current mesh
  20665. */
  20666. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20667. var globalPosition = this.getAbsolutePosition();
  20668. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20669. if (!this._collider) {
  20670. this._collider = new BABYLON.Collider();
  20671. }
  20672. this._collider._radius = this.ellipsoid;
  20673. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20674. return this;
  20675. };
  20676. // Submeshes octree
  20677. /**
  20678. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20679. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20680. * @param maxCapacity defines the maximum size of each block (64 by default)
  20681. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20682. * @returns the new octree
  20683. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20684. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20685. */
  20686. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20687. if (maxCapacity === void 0) { maxCapacity = 64; }
  20688. if (maxDepth === void 0) { maxDepth = 2; }
  20689. if (!this._submeshesOctree) {
  20690. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20691. }
  20692. this.computeWorldMatrix(true);
  20693. var boundingInfo = this.getBoundingInfo();
  20694. // Update octree
  20695. var bbox = boundingInfo.boundingBox;
  20696. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20697. return this._submeshesOctree;
  20698. };
  20699. // Collisions
  20700. /** @hidden */
  20701. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20702. this._generatePointsArray();
  20703. if (!this._positions) {
  20704. return this;
  20705. }
  20706. // Transformation
  20707. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20708. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20709. subMesh._lastColliderWorldVertices = [];
  20710. subMesh._trianglePlanes = [];
  20711. var start = subMesh.verticesStart;
  20712. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20713. for (var i = start; i < end; i++) {
  20714. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20715. }
  20716. }
  20717. // Collide
  20718. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20719. if (collider.collisionFound) {
  20720. collider.collidedMesh = this;
  20721. }
  20722. return this;
  20723. };
  20724. /** @hidden */
  20725. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20726. var subMeshes;
  20727. var len;
  20728. // Octrees
  20729. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20730. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20731. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20732. len = intersections.length;
  20733. subMeshes = intersections.data;
  20734. }
  20735. else {
  20736. subMeshes = this.subMeshes;
  20737. len = subMeshes.length;
  20738. }
  20739. for (var index = 0; index < len; index++) {
  20740. var subMesh = subMeshes[index];
  20741. // Bounding test
  20742. if (len > 1 && !subMesh._checkCollision(collider))
  20743. continue;
  20744. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20745. }
  20746. return this;
  20747. };
  20748. /** @hidden */
  20749. AbstractMesh.prototype._checkCollision = function (collider) {
  20750. // Bounding box test
  20751. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20752. return this;
  20753. // Transformation matrix
  20754. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20755. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20756. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20757. return this;
  20758. };
  20759. // Picking
  20760. /** @hidden */
  20761. AbstractMesh.prototype._generatePointsArray = function () {
  20762. return false;
  20763. };
  20764. /**
  20765. * Checks if the passed Ray intersects with the mesh
  20766. * @param ray defines the ray to use
  20767. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20768. * @returns the picking info
  20769. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20770. */
  20771. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20772. var pickingInfo = new BABYLON.PickingInfo();
  20773. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20774. return pickingInfo;
  20775. }
  20776. if (!this._generatePointsArray()) {
  20777. return pickingInfo;
  20778. }
  20779. var intersectInfo = null;
  20780. // Octrees
  20781. var subMeshes;
  20782. var len;
  20783. if (this._submeshesOctree && this.useOctreeForPicking) {
  20784. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20785. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20786. len = intersections.length;
  20787. subMeshes = intersections.data;
  20788. }
  20789. else {
  20790. subMeshes = this.subMeshes;
  20791. len = subMeshes.length;
  20792. }
  20793. for (var index = 0; index < len; index++) {
  20794. var subMesh = subMeshes[index];
  20795. // Bounding test
  20796. if (len > 1 && !subMesh.canIntersects(ray))
  20797. continue;
  20798. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20799. if (currentIntersectInfo) {
  20800. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20801. intersectInfo = currentIntersectInfo;
  20802. intersectInfo.subMeshId = index;
  20803. if (fastCheck) {
  20804. break;
  20805. }
  20806. }
  20807. }
  20808. }
  20809. if (intersectInfo) {
  20810. // Get picked point
  20811. var world = this.getWorldMatrix();
  20812. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20813. var direction = ray.direction.clone();
  20814. direction = direction.scale(intersectInfo.distance);
  20815. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20816. var pickedPoint = worldOrigin.add(worldDirection);
  20817. // Return result
  20818. pickingInfo.hit = true;
  20819. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20820. pickingInfo.pickedPoint = pickedPoint;
  20821. pickingInfo.pickedMesh = this;
  20822. pickingInfo.bu = intersectInfo.bu || 0;
  20823. pickingInfo.bv = intersectInfo.bv || 0;
  20824. pickingInfo.faceId = intersectInfo.faceId;
  20825. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20826. return pickingInfo;
  20827. }
  20828. return pickingInfo;
  20829. };
  20830. /**
  20831. * Clones the current mesh
  20832. * @param name defines the mesh name
  20833. * @param newParent defines the new mesh parent
  20834. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20835. * @returns the new mesh
  20836. */
  20837. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20838. return null;
  20839. };
  20840. /**
  20841. * Disposes all the submeshes of the current meshnp
  20842. * @returns the current mesh
  20843. */
  20844. AbstractMesh.prototype.releaseSubMeshes = function () {
  20845. if (this.subMeshes) {
  20846. while (this.subMeshes.length) {
  20847. this.subMeshes[0].dispose();
  20848. }
  20849. }
  20850. else {
  20851. this.subMeshes = new Array();
  20852. }
  20853. return this;
  20854. };
  20855. /**
  20856. * Releases resources associated with this abstract mesh.
  20857. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20858. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20859. */
  20860. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20861. var _this = this;
  20862. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20863. var index;
  20864. // Smart Array Retainers.
  20865. this.getScene().freeActiveMeshes();
  20866. this.getScene().freeRenderingGroups();
  20867. // Action manager
  20868. if (this.actionManager !== undefined && this.actionManager !== null) {
  20869. this.actionManager.dispose();
  20870. this.actionManager = null;
  20871. }
  20872. // Skeleton
  20873. this._skeleton = null;
  20874. // Physics
  20875. if (this.physicsImpostor) {
  20876. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20877. }
  20878. // Intersections in progress
  20879. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20880. var other = this._intersectionsInProgress[index];
  20881. var pos = other._intersectionsInProgress.indexOf(this);
  20882. other._intersectionsInProgress.splice(pos, 1);
  20883. }
  20884. this._intersectionsInProgress = [];
  20885. // Lights
  20886. var lights = this.getScene().lights;
  20887. lights.forEach(function (light) {
  20888. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20889. if (meshIndex !== -1) {
  20890. light.includedOnlyMeshes.splice(meshIndex, 1);
  20891. }
  20892. meshIndex = light.excludedMeshes.indexOf(_this);
  20893. if (meshIndex !== -1) {
  20894. light.excludedMeshes.splice(meshIndex, 1);
  20895. }
  20896. // Shadow generators
  20897. var generator = light.getShadowGenerator();
  20898. if (generator) {
  20899. var shadowMap = generator.getShadowMap();
  20900. if (shadowMap && shadowMap.renderList) {
  20901. meshIndex = shadowMap.renderList.indexOf(_this);
  20902. if (meshIndex !== -1) {
  20903. shadowMap.renderList.splice(meshIndex, 1);
  20904. }
  20905. }
  20906. }
  20907. });
  20908. // Edges
  20909. if (this._edgesRenderer) {
  20910. this._edgesRenderer.dispose();
  20911. this._edgesRenderer = null;
  20912. }
  20913. // SubMeshes
  20914. if (this.getClassName() !== "InstancedMesh") {
  20915. this.releaseSubMeshes();
  20916. }
  20917. // Octree
  20918. var sceneOctree = this.getScene().selectionOctree;
  20919. if (sceneOctree !== undefined && sceneOctree !== null) {
  20920. var index = sceneOctree.dynamicContent.indexOf(this);
  20921. if (index !== -1) {
  20922. sceneOctree.dynamicContent.splice(index, 1);
  20923. }
  20924. }
  20925. // Query
  20926. var engine = this.getScene().getEngine();
  20927. if (this._occlusionQuery) {
  20928. this._isOcclusionQueryInProgress = false;
  20929. engine.deleteQuery(this._occlusionQuery);
  20930. this._occlusionQuery = null;
  20931. }
  20932. // Engine
  20933. engine.wipeCaches();
  20934. // Remove from scene
  20935. this.getScene().removeMesh(this);
  20936. if (disposeMaterialAndTextures) {
  20937. if (this.material) {
  20938. this.material.dispose(false, true);
  20939. }
  20940. }
  20941. if (!doNotRecurse) {
  20942. // Particles
  20943. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20944. if (this.getScene().particleSystems[index].emitter === this) {
  20945. this.getScene().particleSystems[index].dispose();
  20946. index--;
  20947. }
  20948. }
  20949. }
  20950. // facet data
  20951. if (this._facetDataEnabled) {
  20952. this.disableFacetData();
  20953. }
  20954. this.onAfterWorldMatrixUpdateObservable.clear();
  20955. this.onCollideObservable.clear();
  20956. this.onCollisionPositionChangeObservable.clear();
  20957. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20958. };
  20959. /**
  20960. * Adds the passed mesh as a child to the current mesh
  20961. * @param mesh defines the child mesh
  20962. * @returns the current mesh
  20963. */
  20964. AbstractMesh.prototype.addChild = function (mesh) {
  20965. mesh.setParent(this);
  20966. return this;
  20967. };
  20968. /**
  20969. * Removes the passed mesh from the current mesh children list
  20970. * @param mesh defines the child mesh
  20971. * @returns the current mesh
  20972. */
  20973. AbstractMesh.prototype.removeChild = function (mesh) {
  20974. mesh.setParent(null);
  20975. return this;
  20976. };
  20977. // Facet data
  20978. /** @hidden */
  20979. AbstractMesh.prototype._initFacetData = function () {
  20980. if (!this._facetNormals) {
  20981. this._facetNormals = new Array();
  20982. }
  20983. if (!this._facetPositions) {
  20984. this._facetPositions = new Array();
  20985. }
  20986. if (!this._facetPartitioning) {
  20987. this._facetPartitioning = new Array();
  20988. }
  20989. this._facetNb = (this.getIndices().length / 3) | 0;
  20990. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20991. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20992. for (var f = 0; f < this._facetNb; f++) {
  20993. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20994. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20995. }
  20996. this._facetDataEnabled = true;
  20997. return this;
  20998. };
  20999. /**
  21000. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21001. * This method can be called within the render loop.
  21002. * 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
  21003. * @returns the current mesh
  21004. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21005. */
  21006. AbstractMesh.prototype.updateFacetData = function () {
  21007. if (!this._facetDataEnabled) {
  21008. this._initFacetData();
  21009. }
  21010. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21011. var indices = this.getIndices();
  21012. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21013. var bInfo = this.getBoundingInfo();
  21014. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21015. // init arrays, matrix and sort function on first call
  21016. this._facetDepthSortEnabled = true;
  21017. if (indices instanceof Uint16Array) {
  21018. this._depthSortedIndices = new Uint16Array(indices);
  21019. }
  21020. else if (indices instanceof Uint32Array) {
  21021. this._depthSortedIndices = new Uint32Array(indices);
  21022. }
  21023. else {
  21024. var needs32bits = false;
  21025. for (var i = 0; i < indices.length; i++) {
  21026. if (indices[i] > 65535) {
  21027. needs32bits = true;
  21028. break;
  21029. }
  21030. }
  21031. if (needs32bits) {
  21032. this._depthSortedIndices = new Uint32Array(indices);
  21033. }
  21034. else {
  21035. this._depthSortedIndices = new Uint16Array(indices);
  21036. }
  21037. }
  21038. this._facetDepthSortFunction = function (f1, f2) {
  21039. return (f2.sqDistance - f1.sqDistance);
  21040. };
  21041. if (!this._facetDepthSortFrom) {
  21042. var camera = this.getScene().activeCamera;
  21043. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21044. }
  21045. this._depthSortedFacets = [];
  21046. for (var f = 0; f < this._facetNb; f++) {
  21047. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21048. this._depthSortedFacets.push(depthSortedFacet);
  21049. }
  21050. this._invertedMatrix = BABYLON.Matrix.Identity();
  21051. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21052. }
  21053. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21054. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21055. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21056. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21057. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21058. this._subDiv.max = this._partitioningSubdivisions;
  21059. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21060. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21061. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21062. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21063. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21064. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21065. // set the parameters for ComputeNormals()
  21066. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21067. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21068. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21069. this._facetParameters.bInfo = bInfo;
  21070. this._facetParameters.bbSize = this._bbSize;
  21071. this._facetParameters.subDiv = this._subDiv;
  21072. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21073. this._facetParameters.depthSort = this._facetDepthSort;
  21074. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21075. this.computeWorldMatrix(true);
  21076. this._worldMatrix.invertToRef(this._invertedMatrix);
  21077. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21078. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21079. }
  21080. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21081. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21082. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21083. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21084. var l = (this._depthSortedIndices.length / 3) | 0;
  21085. for (var f = 0; f < l; f++) {
  21086. var sind = this._depthSortedFacets[f].ind;
  21087. this._depthSortedIndices[f * 3] = indices[sind];
  21088. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21089. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21090. }
  21091. this.updateIndices(this._depthSortedIndices);
  21092. }
  21093. return this;
  21094. };
  21095. /**
  21096. * Returns the facetLocalNormals array.
  21097. * The normals are expressed in the mesh local spac
  21098. * @returns an array of Vector3
  21099. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21100. */
  21101. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21102. if (!this._facetNormals) {
  21103. this.updateFacetData();
  21104. }
  21105. return this._facetNormals;
  21106. };
  21107. /**
  21108. * Returns the facetLocalPositions array.
  21109. * The facet positions are expressed in the mesh local space
  21110. * @returns an array of Vector3
  21111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21112. */
  21113. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21114. if (!this._facetPositions) {
  21115. this.updateFacetData();
  21116. }
  21117. return this._facetPositions;
  21118. };
  21119. /**
  21120. * Returns the facetLocalPartioning array
  21121. * @returns an array of array of numbers
  21122. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21123. */
  21124. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21125. if (!this._facetPartitioning) {
  21126. this.updateFacetData();
  21127. }
  21128. return this._facetPartitioning;
  21129. };
  21130. /**
  21131. * Returns the i-th facet position in the world system.
  21132. * This method allocates a new Vector3 per call
  21133. * @param i defines the facet index
  21134. * @returns a new Vector3
  21135. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21136. */
  21137. AbstractMesh.prototype.getFacetPosition = function (i) {
  21138. var pos = BABYLON.Vector3.Zero();
  21139. this.getFacetPositionToRef(i, pos);
  21140. return pos;
  21141. };
  21142. /**
  21143. * Sets the reference Vector3 with the i-th facet position in the world system
  21144. * @param i defines the facet index
  21145. * @param ref defines the target vector
  21146. * @returns the current mesh
  21147. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21148. */
  21149. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21150. var localPos = (this.getFacetLocalPositions())[i];
  21151. var world = this.getWorldMatrix();
  21152. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21153. return this;
  21154. };
  21155. /**
  21156. * Returns the i-th facet normal in the world system.
  21157. * This method allocates a new Vector3 per call
  21158. * @param i defines the facet index
  21159. * @returns a new Vector3
  21160. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21161. */
  21162. AbstractMesh.prototype.getFacetNormal = function (i) {
  21163. var norm = BABYLON.Vector3.Zero();
  21164. this.getFacetNormalToRef(i, norm);
  21165. return norm;
  21166. };
  21167. /**
  21168. * Sets the reference Vector3 with the i-th facet normal in the world system
  21169. * @param i defines the facet index
  21170. * @param ref defines the target vector
  21171. * @returns the current mesh
  21172. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21173. */
  21174. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21175. var localNorm = (this.getFacetLocalNormals())[i];
  21176. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21177. return this;
  21178. };
  21179. /**
  21180. * 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)
  21181. * @param x defines x coordinate
  21182. * @param y defines y coordinate
  21183. * @param z defines z coordinate
  21184. * @returns the array of facet indexes
  21185. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21186. */
  21187. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21188. var bInfo = this.getBoundingInfo();
  21189. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21190. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21191. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21192. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21193. return null;
  21194. }
  21195. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21196. };
  21197. /**
  21198. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21199. * @param projected sets as the (x,y,z) world projection on the facet
  21200. * @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
  21201. * @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
  21202. * @param x defines x coordinate
  21203. * @param y defines y coordinate
  21204. * @param z defines z coordinate
  21205. * @returns the face index if found (or null instead)
  21206. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21207. */
  21208. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21209. if (checkFace === void 0) { checkFace = false; }
  21210. if (facing === void 0) { facing = true; }
  21211. var world = this.getWorldMatrix();
  21212. var invMat = BABYLON.Tmp.Matrix[5];
  21213. world.invertToRef(invMat);
  21214. var invVect = BABYLON.Tmp.Vector3[8];
  21215. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21216. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21217. if (projected) {
  21218. // tranform the local computed projected vector to world coordinates
  21219. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21220. }
  21221. return closest;
  21222. };
  21223. /**
  21224. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21225. * @param projected sets as the (x,y,z) local projection on the facet
  21226. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21227. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21228. * @param x defines x coordinate
  21229. * @param y defines y coordinate
  21230. * @param z defines z coordinate
  21231. * @returns the face index if found (or null instead)
  21232. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21233. */
  21234. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21235. if (checkFace === void 0) { checkFace = false; }
  21236. if (facing === void 0) { facing = true; }
  21237. var closest = null;
  21238. var tmpx = 0.0;
  21239. var tmpy = 0.0;
  21240. var tmpz = 0.0;
  21241. var d = 0.0; // tmp dot facet normal * facet position
  21242. var t0 = 0.0;
  21243. var projx = 0.0;
  21244. var projy = 0.0;
  21245. var projz = 0.0;
  21246. // Get all the facets in the same partitioning block than (x, y, z)
  21247. var facetPositions = this.getFacetLocalPositions();
  21248. var facetNormals = this.getFacetLocalNormals();
  21249. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21250. if (!facetsInBlock) {
  21251. return null;
  21252. }
  21253. // Get the closest facet to (x, y, z)
  21254. var shortest = Number.MAX_VALUE; // init distance vars
  21255. var tmpDistance = shortest;
  21256. var fib; // current facet in the block
  21257. var norm; // current facet normal
  21258. var p0; // current facet barycenter position
  21259. // loop on all the facets in the current partitioning block
  21260. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21261. fib = facetsInBlock[idx];
  21262. norm = facetNormals[fib];
  21263. p0 = facetPositions[fib];
  21264. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21265. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21266. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21267. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21268. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21269. projx = x + norm.x * t0;
  21270. projy = y + norm.y * t0;
  21271. projz = z + norm.z * t0;
  21272. tmpx = projx - x;
  21273. tmpy = projy - y;
  21274. tmpz = projz - z;
  21275. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21276. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21277. shortest = tmpDistance;
  21278. closest = fib;
  21279. if (projected) {
  21280. projected.x = projx;
  21281. projected.y = projy;
  21282. projected.z = projz;
  21283. }
  21284. }
  21285. }
  21286. }
  21287. return closest;
  21288. };
  21289. /**
  21290. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21291. * @returns the parameters
  21292. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21293. */
  21294. AbstractMesh.prototype.getFacetDataParameters = function () {
  21295. return this._facetParameters;
  21296. };
  21297. /**
  21298. * Disables the feature FacetData and frees the related memory
  21299. * @returns the current mesh
  21300. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21301. */
  21302. AbstractMesh.prototype.disableFacetData = function () {
  21303. if (this._facetDataEnabled) {
  21304. this._facetDataEnabled = false;
  21305. this._facetPositions = new Array();
  21306. this._facetNormals = new Array();
  21307. this._facetPartitioning = new Array();
  21308. this._facetParameters = null;
  21309. this._depthSortedIndices = new Uint32Array(0);
  21310. }
  21311. return this;
  21312. };
  21313. /**
  21314. * Updates the AbstractMesh indices array
  21315. * @param indices defines the data source
  21316. * @returns the current mesh
  21317. */
  21318. AbstractMesh.prototype.updateIndices = function (indices) {
  21319. return this;
  21320. };
  21321. /**
  21322. * Creates new normals data for the mesh
  21323. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21324. * @returns the current mesh
  21325. */
  21326. AbstractMesh.prototype.createNormals = function (updatable) {
  21327. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21328. var indices = this.getIndices();
  21329. var normals;
  21330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21331. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21332. }
  21333. else {
  21334. normals = [];
  21335. }
  21336. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21337. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21338. return this;
  21339. };
  21340. /**
  21341. * Align the mesh with a normal
  21342. * @param normal defines the normal to use
  21343. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21344. * @returns the current mesh
  21345. */
  21346. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21347. if (!upDirection) {
  21348. upDirection = BABYLON.Axis.Y;
  21349. }
  21350. var axisX = BABYLON.Tmp.Vector3[0];
  21351. var axisZ = BABYLON.Tmp.Vector3[1];
  21352. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21353. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21354. if (this.rotationQuaternion) {
  21355. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21356. }
  21357. else {
  21358. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21359. }
  21360. return this;
  21361. };
  21362. /** @hidden */
  21363. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21364. var engine = this.getEngine();
  21365. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21366. this._isOccluded = false;
  21367. return;
  21368. }
  21369. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21370. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21371. if (isOcclusionQueryAvailable) {
  21372. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21373. this._isOcclusionQueryInProgress = false;
  21374. this._occlusionInternalRetryCounter = 0;
  21375. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21376. }
  21377. else {
  21378. this._occlusionInternalRetryCounter++;
  21379. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21380. this._isOcclusionQueryInProgress = false;
  21381. this._occlusionInternalRetryCounter = 0;
  21382. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21383. // if strict continue the last state of the object.
  21384. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21385. }
  21386. else {
  21387. return;
  21388. }
  21389. }
  21390. }
  21391. var scene = this.getScene();
  21392. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21393. if (!this._occlusionQuery) {
  21394. this._occlusionQuery = engine.createQuery();
  21395. }
  21396. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21397. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21398. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21399. this._isOcclusionQueryInProgress = true;
  21400. };
  21401. /** No occlusion */
  21402. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21403. /** Occlusion set to optimisitic */
  21404. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21405. /** Occlusion set to strict */
  21406. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21407. /** Use an accurante occlusion algorithm */
  21408. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21409. /** Use a conservative occlusion algorithm */
  21410. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21411. return AbstractMesh;
  21412. }(BABYLON.TransformNode));
  21413. BABYLON.AbstractMesh = AbstractMesh;
  21414. })(BABYLON || (BABYLON = {}));
  21415. //# sourceMappingURL=babylon.abstractMesh.js.map
  21416. var BABYLON;
  21417. (function (BABYLON) {
  21418. /**
  21419. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21420. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21421. * 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.
  21422. */
  21423. var Light = /** @class */ (function (_super) {
  21424. __extends(Light, _super);
  21425. /**
  21426. * Creates a Light object in the scene.
  21427. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21428. * @param name The firendly name of the light
  21429. * @param scene The scene the light belongs too
  21430. */
  21431. function Light(name, scene) {
  21432. var _this = _super.call(this, name, scene) || this;
  21433. /**
  21434. * Diffuse gives the basic color to an object.
  21435. */
  21436. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21437. /**
  21438. * Specular produces a highlight color on an object.
  21439. * Note: This is note affecting PBR materials.
  21440. */
  21441. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21442. /**
  21443. * Strength of the light.
  21444. * Note: By default it is define in the framework own unit.
  21445. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21446. */
  21447. _this.intensity = 1.0;
  21448. /**
  21449. * Defines how far from the source the light is impacting in scene units.
  21450. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21451. */
  21452. _this.range = Number.MAX_VALUE;
  21453. /**
  21454. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21455. * of light.
  21456. */
  21457. _this._photometricScale = 1.0;
  21458. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21459. _this._radius = 0.00001;
  21460. /**
  21461. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21462. * exceeding the number allowed of the materials.
  21463. */
  21464. _this.renderPriority = 0;
  21465. _this._shadowEnabled = true;
  21466. _this._excludeWithLayerMask = 0;
  21467. _this._includeOnlyWithLayerMask = 0;
  21468. _this._lightmapMode = 0;
  21469. /**
  21470. * @hidden Internal use only.
  21471. */
  21472. _this._excludedMeshesIds = new Array();
  21473. /**
  21474. * @hidden Internal use only.
  21475. */
  21476. _this._includedOnlyMeshesIds = new Array();
  21477. _this.getScene().addLight(_this);
  21478. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21479. _this._buildUniformLayout();
  21480. _this.includedOnlyMeshes = new Array();
  21481. _this.excludedMeshes = new Array();
  21482. _this._resyncMeshes();
  21483. return _this;
  21484. }
  21485. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21486. /**
  21487. * If every light affecting the material is in this lightmapMode,
  21488. * material.lightmapTexture adds or multiplies
  21489. * (depends on material.useLightmapAsShadowmap)
  21490. * after every other light calculations.
  21491. */
  21492. get: function () {
  21493. return Light._LIGHTMAP_DEFAULT;
  21494. },
  21495. enumerable: true,
  21496. configurable: true
  21497. });
  21498. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21499. /**
  21500. * material.lightmapTexture as only diffuse lighting from this light
  21501. * adds only specular lighting from this light
  21502. * adds dynamic shadows
  21503. */
  21504. get: function () {
  21505. return Light._LIGHTMAP_SPECULAR;
  21506. },
  21507. enumerable: true,
  21508. configurable: true
  21509. });
  21510. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21511. /**
  21512. * material.lightmapTexture as only lighting
  21513. * no light calculation from this light
  21514. * only adds dynamic shadows from this light
  21515. */
  21516. get: function () {
  21517. return Light._LIGHTMAP_SHADOWSONLY;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21523. /**
  21524. * Each light type uses the default quantity according to its type:
  21525. * point/spot lights use luminous intensity
  21526. * directional lights use illuminance
  21527. */
  21528. get: function () {
  21529. return Light._INTENSITYMODE_AUTOMATIC;
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21535. /**
  21536. * lumen (lm)
  21537. */
  21538. get: function () {
  21539. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21540. },
  21541. enumerable: true,
  21542. configurable: true
  21543. });
  21544. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21545. /**
  21546. * candela (lm/sr)
  21547. */
  21548. get: function () {
  21549. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21550. },
  21551. enumerable: true,
  21552. configurable: true
  21553. });
  21554. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21555. /**
  21556. * lux (lm/m^2)
  21557. */
  21558. get: function () {
  21559. return Light._INTENSITYMODE_ILLUMINANCE;
  21560. },
  21561. enumerable: true,
  21562. configurable: true
  21563. });
  21564. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21565. /**
  21566. * nit (cd/m^2)
  21567. */
  21568. get: function () {
  21569. return Light._INTENSITYMODE_LUMINANCE;
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21575. /**
  21576. * Light type const id of the point light.
  21577. */
  21578. get: function () {
  21579. return Light._LIGHTTYPEID_POINTLIGHT;
  21580. },
  21581. enumerable: true,
  21582. configurable: true
  21583. });
  21584. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21585. /**
  21586. * Light type const id of the directional light.
  21587. */
  21588. get: function () {
  21589. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21590. },
  21591. enumerable: true,
  21592. configurable: true
  21593. });
  21594. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21595. /**
  21596. * Light type const id of the spot light.
  21597. */
  21598. get: function () {
  21599. return Light._LIGHTTYPEID_SPOTLIGHT;
  21600. },
  21601. enumerable: true,
  21602. configurable: true
  21603. });
  21604. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21605. /**
  21606. * Light type const id of the hemispheric light.
  21607. */
  21608. get: function () {
  21609. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21610. },
  21611. enumerable: true,
  21612. configurable: true
  21613. });
  21614. Object.defineProperty(Light.prototype, "intensityMode", {
  21615. /**
  21616. * Gets the photometric scale used to interpret the intensity.
  21617. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21618. */
  21619. get: function () {
  21620. return this._intensityMode;
  21621. },
  21622. /**
  21623. * Sets the photometric scale used to interpret the intensity.
  21624. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21625. */
  21626. set: function (value) {
  21627. this._intensityMode = value;
  21628. this._computePhotometricScale();
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. ;
  21634. ;
  21635. Object.defineProperty(Light.prototype, "radius", {
  21636. /**
  21637. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21638. */
  21639. get: function () {
  21640. return this._radius;
  21641. },
  21642. /**
  21643. * sets the light radius used by PBR Materials to simulate soft area lights.
  21644. */
  21645. set: function (value) {
  21646. this._radius = value;
  21647. this._computePhotometricScale();
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. ;
  21653. ;
  21654. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21655. /**
  21656. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21657. * the current shadow generator.
  21658. */
  21659. get: function () {
  21660. return this._shadowEnabled;
  21661. },
  21662. /**
  21663. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21664. * the current shadow generator.
  21665. */
  21666. set: function (value) {
  21667. if (this._shadowEnabled === value) {
  21668. return;
  21669. }
  21670. this._shadowEnabled = value;
  21671. this._markMeshesAsLightDirty();
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21677. /**
  21678. * Gets the only meshes impacted by this light.
  21679. */
  21680. get: function () {
  21681. return this._includedOnlyMeshes;
  21682. },
  21683. /**
  21684. * Sets the only meshes impacted by this light.
  21685. */
  21686. set: function (value) {
  21687. this._includedOnlyMeshes = value;
  21688. this._hookArrayForIncludedOnly(value);
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21694. /**
  21695. * Gets the meshes not impacted by this light.
  21696. */
  21697. get: function () {
  21698. return this._excludedMeshes;
  21699. },
  21700. /**
  21701. * Sets the meshes not impacted by this light.
  21702. */
  21703. set: function (value) {
  21704. this._excludedMeshes = value;
  21705. this._hookArrayForExcluded(value);
  21706. },
  21707. enumerable: true,
  21708. configurable: true
  21709. });
  21710. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21711. /**
  21712. * Gets the layer id use to find what meshes are not impacted by the light.
  21713. * Inactive if 0
  21714. */
  21715. get: function () {
  21716. return this._excludeWithLayerMask;
  21717. },
  21718. /**
  21719. * Sets the layer id use to find what meshes are not impacted by the light.
  21720. * Inactive if 0
  21721. */
  21722. set: function (value) {
  21723. this._excludeWithLayerMask = value;
  21724. this._resyncMeshes();
  21725. },
  21726. enumerable: true,
  21727. configurable: true
  21728. });
  21729. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21730. /**
  21731. * Gets the layer id use to find what meshes are impacted by the light.
  21732. * Inactive if 0
  21733. */
  21734. get: function () {
  21735. return this._includeOnlyWithLayerMask;
  21736. },
  21737. /**
  21738. * Sets the layer id use to find what meshes are impacted by the light.
  21739. * Inactive if 0
  21740. */
  21741. set: function (value) {
  21742. this._includeOnlyWithLayerMask = value;
  21743. this._resyncMeshes();
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Light.prototype, "lightmapMode", {
  21749. /**
  21750. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21751. */
  21752. get: function () {
  21753. return this._lightmapMode;
  21754. },
  21755. /**
  21756. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21757. */
  21758. set: function (value) {
  21759. if (this._lightmapMode === value) {
  21760. return;
  21761. }
  21762. this._lightmapMode = value;
  21763. this._markMeshesAsLightDirty();
  21764. },
  21765. enumerable: true,
  21766. configurable: true
  21767. });
  21768. /**
  21769. * Returns the string "Light".
  21770. * @returns the class name
  21771. */
  21772. Light.prototype.getClassName = function () {
  21773. return "Light";
  21774. };
  21775. /**
  21776. * Converts the light information to a readable string for debug purpose.
  21777. * @param fullDetails Supports for multiple levels of logging within scene loading
  21778. * @returns the human readable light info
  21779. */
  21780. Light.prototype.toString = function (fullDetails) {
  21781. var ret = "Name: " + this.name;
  21782. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21783. if (this.animations) {
  21784. for (var i = 0; i < this.animations.length; i++) {
  21785. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21786. }
  21787. }
  21788. if (fullDetails) {
  21789. }
  21790. return ret;
  21791. };
  21792. /**
  21793. * Set the enabled state of this node.
  21794. * @param value - the new enabled state
  21795. */
  21796. Light.prototype.setEnabled = function (value) {
  21797. _super.prototype.setEnabled.call(this, value);
  21798. this._resyncMeshes();
  21799. };
  21800. /**
  21801. * Returns the Light associated shadow generator if any.
  21802. * @return the associated shadow generator.
  21803. */
  21804. Light.prototype.getShadowGenerator = function () {
  21805. return this._shadowGenerator;
  21806. };
  21807. /**
  21808. * Returns a Vector3, the absolute light position in the World.
  21809. * @returns the world space position of the light
  21810. */
  21811. Light.prototype.getAbsolutePosition = function () {
  21812. return BABYLON.Vector3.Zero();
  21813. };
  21814. /**
  21815. * Specifies if the light will affect the passed mesh.
  21816. * @param mesh The mesh to test against the light
  21817. * @return true the mesh is affected otherwise, false.
  21818. */
  21819. Light.prototype.canAffectMesh = function (mesh) {
  21820. if (!mesh) {
  21821. return true;
  21822. }
  21823. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21824. return false;
  21825. }
  21826. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21827. return false;
  21828. }
  21829. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21830. return false;
  21831. }
  21832. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21833. return false;
  21834. }
  21835. return true;
  21836. };
  21837. /**
  21838. * Computes and Returns the light World matrix.
  21839. * @returns the world matrix
  21840. */
  21841. Light.prototype.getWorldMatrix = function () {
  21842. this._currentRenderId = this.getScene().getRenderId();
  21843. this._childRenderId = this._currentRenderId;
  21844. var worldMatrix = this._getWorldMatrix();
  21845. if (this.parent && this.parent.getWorldMatrix) {
  21846. if (!this._parentedWorldMatrix) {
  21847. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21848. }
  21849. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21850. this._markSyncedWithParent();
  21851. return this._parentedWorldMatrix;
  21852. }
  21853. return worldMatrix;
  21854. };
  21855. /**
  21856. * Sort function to order lights for rendering.
  21857. * @param a First Light object to compare to second.
  21858. * @param b Second Light object to compare first.
  21859. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21860. */
  21861. Light.CompareLightsPriority = function (a, b) {
  21862. //shadow-casting lights have priority over non-shadow-casting lights
  21863. //the renderPrioirty is a secondary sort criterion
  21864. if (a.shadowEnabled !== b.shadowEnabled) {
  21865. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21866. }
  21867. return b.renderPriority - a.renderPriority;
  21868. };
  21869. /**
  21870. * Releases resources associated with this node.
  21871. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21872. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21873. */
  21874. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21875. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21876. if (this._shadowGenerator) {
  21877. this._shadowGenerator.dispose();
  21878. this._shadowGenerator = null;
  21879. }
  21880. // Animations
  21881. this.getScene().stopAnimation(this);
  21882. // Remove from meshes
  21883. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21884. var mesh = _a[_i];
  21885. mesh._removeLightSource(this);
  21886. }
  21887. this._uniformBuffer.dispose();
  21888. // Remove from scene
  21889. this.getScene().removeLight(this);
  21890. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21891. };
  21892. /**
  21893. * Returns the light type ID (integer).
  21894. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21895. */
  21896. Light.prototype.getTypeID = function () {
  21897. return 0;
  21898. };
  21899. /**
  21900. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21901. * @returns the scaled intensity in intensity mode unit
  21902. */
  21903. Light.prototype.getScaledIntensity = function () {
  21904. return this._photometricScale * this.intensity;
  21905. };
  21906. /**
  21907. * Returns a new Light object, named "name", from the current one.
  21908. * @param name The name of the cloned light
  21909. * @returns the new created light
  21910. */
  21911. Light.prototype.clone = function (name) {
  21912. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21913. if (!constructor) {
  21914. return null;
  21915. }
  21916. return BABYLON.SerializationHelper.Clone(constructor, this);
  21917. };
  21918. /**
  21919. * Serializes the current light into a Serialization object.
  21920. * @returns the serialized object.
  21921. */
  21922. Light.prototype.serialize = function () {
  21923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21924. // Type
  21925. serializationObject.type = this.getTypeID();
  21926. // Parent
  21927. if (this.parent) {
  21928. serializationObject.parentId = this.parent.id;
  21929. }
  21930. // Inclusion / exclusions
  21931. if (this.excludedMeshes.length > 0) {
  21932. serializationObject.excludedMeshesIds = [];
  21933. this.excludedMeshes.forEach(function (mesh) {
  21934. serializationObject.excludedMeshesIds.push(mesh.id);
  21935. });
  21936. }
  21937. if (this.includedOnlyMeshes.length > 0) {
  21938. serializationObject.includedOnlyMeshesIds = [];
  21939. this.includedOnlyMeshes.forEach(function (mesh) {
  21940. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21941. });
  21942. }
  21943. // Animations
  21944. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21945. serializationObject.ranges = this.serializeAnimationRanges();
  21946. return serializationObject;
  21947. };
  21948. /**
  21949. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21950. * This new light is named "name" and added to the passed scene.
  21951. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21952. * @param name The friendly name of the light
  21953. * @param scene The scene the new light will belong to
  21954. * @returns the constructor function
  21955. */
  21956. Light.GetConstructorFromName = function (type, name, scene) {
  21957. switch (type) {
  21958. case 0:
  21959. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21960. case 1:
  21961. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21962. case 2:
  21963. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21964. case 3:
  21965. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21966. }
  21967. return null;
  21968. };
  21969. /**
  21970. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21971. * @param parsedLight The JSON representation of the light
  21972. * @param scene The scene to create the parsed light in
  21973. * @returns the created light after parsing
  21974. */
  21975. Light.Parse = function (parsedLight, scene) {
  21976. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21977. if (!constructor) {
  21978. return null;
  21979. }
  21980. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21981. // Inclusion / exclusions
  21982. if (parsedLight.excludedMeshesIds) {
  21983. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21984. }
  21985. if (parsedLight.includedOnlyMeshesIds) {
  21986. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21987. }
  21988. // Parent
  21989. if (parsedLight.parentId) {
  21990. light._waitingParentId = parsedLight.parentId;
  21991. }
  21992. // Animations
  21993. if (parsedLight.animations) {
  21994. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21995. var parsedAnimation = parsedLight.animations[animationIndex];
  21996. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21997. }
  21998. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21999. }
  22000. if (parsedLight.autoAnimate) {
  22001. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22002. }
  22003. return light;
  22004. };
  22005. Light.prototype._hookArrayForExcluded = function (array) {
  22006. var _this = this;
  22007. var oldPush = array.push;
  22008. array.push = function () {
  22009. var items = [];
  22010. for (var _i = 0; _i < arguments.length; _i++) {
  22011. items[_i] = arguments[_i];
  22012. }
  22013. var result = oldPush.apply(array, items);
  22014. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22015. var item = items_1[_a];
  22016. item._resyncLighSource(_this);
  22017. }
  22018. return result;
  22019. };
  22020. var oldSplice = array.splice;
  22021. array.splice = function (index, deleteCount) {
  22022. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22023. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22024. var item = deleted_1[_i];
  22025. item._resyncLighSource(_this);
  22026. }
  22027. return deleted;
  22028. };
  22029. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22030. var item = array_1[_i];
  22031. item._resyncLighSource(this);
  22032. }
  22033. };
  22034. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22035. var _this = this;
  22036. var oldPush = array.push;
  22037. array.push = function () {
  22038. var items = [];
  22039. for (var _i = 0; _i < arguments.length; _i++) {
  22040. items[_i] = arguments[_i];
  22041. }
  22042. var result = oldPush.apply(array, items);
  22043. _this._resyncMeshes();
  22044. return result;
  22045. };
  22046. var oldSplice = array.splice;
  22047. array.splice = function (index, deleteCount) {
  22048. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22049. _this._resyncMeshes();
  22050. return deleted;
  22051. };
  22052. this._resyncMeshes();
  22053. };
  22054. Light.prototype._resyncMeshes = function () {
  22055. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22056. var mesh = _a[_i];
  22057. mesh._resyncLighSource(this);
  22058. }
  22059. };
  22060. /**
  22061. * Forces the meshes to update their light related information in their rendering used effects
  22062. * @hidden Internal Use Only
  22063. */
  22064. Light.prototype._markMeshesAsLightDirty = function () {
  22065. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22066. var mesh = _a[_i];
  22067. if (mesh._lightSources.indexOf(this) !== -1) {
  22068. mesh._markSubMeshesAsLightDirty();
  22069. }
  22070. }
  22071. };
  22072. /**
  22073. * Recomputes the cached photometric scale if needed.
  22074. */
  22075. Light.prototype._computePhotometricScale = function () {
  22076. this._photometricScale = this._getPhotometricScale();
  22077. this.getScene().resetCachedMaterial();
  22078. };
  22079. /**
  22080. * Returns the Photometric Scale according to the light type and intensity mode.
  22081. */
  22082. Light.prototype._getPhotometricScale = function () {
  22083. var photometricScale = 0.0;
  22084. var lightTypeID = this.getTypeID();
  22085. //get photometric mode
  22086. var photometricMode = this.intensityMode;
  22087. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22088. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22089. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22090. }
  22091. else {
  22092. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22093. }
  22094. }
  22095. //compute photometric scale
  22096. switch (lightTypeID) {
  22097. case Light.LIGHTTYPEID_POINTLIGHT:
  22098. case Light.LIGHTTYPEID_SPOTLIGHT:
  22099. switch (photometricMode) {
  22100. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22101. photometricScale = 1.0 / (4.0 * Math.PI);
  22102. break;
  22103. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22104. photometricScale = 1.0;
  22105. break;
  22106. case Light.INTENSITYMODE_LUMINANCE:
  22107. photometricScale = this.radius * this.radius;
  22108. break;
  22109. }
  22110. break;
  22111. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22112. switch (photometricMode) {
  22113. case Light.INTENSITYMODE_ILLUMINANCE:
  22114. photometricScale = 1.0;
  22115. break;
  22116. case Light.INTENSITYMODE_LUMINANCE:
  22117. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22118. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22119. var apexAngleRadians = this.radius;
  22120. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22121. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22122. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22123. photometricScale = solidAngle;
  22124. break;
  22125. }
  22126. break;
  22127. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22128. // No fall off in hemisperic light.
  22129. photometricScale = 1.0;
  22130. break;
  22131. }
  22132. return photometricScale;
  22133. };
  22134. /**
  22135. * Reorder the light in the scene according to their defined priority.
  22136. * @hidden Internal Use Only
  22137. */
  22138. Light.prototype._reorderLightsInScene = function () {
  22139. var scene = this.getScene();
  22140. if (this._renderPriority != 0) {
  22141. scene.requireLightSorting = true;
  22142. }
  22143. this.getScene().sortLightsByPriority();
  22144. };
  22145. //lightmapMode Consts
  22146. Light._LIGHTMAP_DEFAULT = 0;
  22147. Light._LIGHTMAP_SPECULAR = 1;
  22148. Light._LIGHTMAP_SHADOWSONLY = 2;
  22149. // Intensity Mode Consts
  22150. Light._INTENSITYMODE_AUTOMATIC = 0;
  22151. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22152. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22153. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22154. Light._INTENSITYMODE_LUMINANCE = 4;
  22155. // Light types ids const.
  22156. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22157. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22158. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22159. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22160. __decorate([
  22161. BABYLON.serializeAsColor3()
  22162. ], Light.prototype, "diffuse", void 0);
  22163. __decorate([
  22164. BABYLON.serializeAsColor3()
  22165. ], Light.prototype, "specular", void 0);
  22166. __decorate([
  22167. BABYLON.serialize()
  22168. ], Light.prototype, "intensity", void 0);
  22169. __decorate([
  22170. BABYLON.serialize()
  22171. ], Light.prototype, "range", void 0);
  22172. __decorate([
  22173. BABYLON.serialize()
  22174. ], Light.prototype, "intensityMode", null);
  22175. __decorate([
  22176. BABYLON.serialize()
  22177. ], Light.prototype, "radius", null);
  22178. __decorate([
  22179. BABYLON.serialize()
  22180. ], Light.prototype, "_renderPriority", void 0);
  22181. __decorate([
  22182. BABYLON.expandToProperty("_reorderLightsInScene")
  22183. ], Light.prototype, "renderPriority", void 0);
  22184. __decorate([
  22185. BABYLON.serialize("shadowEnabled")
  22186. ], Light.prototype, "_shadowEnabled", void 0);
  22187. __decorate([
  22188. BABYLON.serialize("excludeWithLayerMask")
  22189. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22190. __decorate([
  22191. BABYLON.serialize("includeOnlyWithLayerMask")
  22192. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22193. __decorate([
  22194. BABYLON.serialize("lightmapMode")
  22195. ], Light.prototype, "_lightmapMode", void 0);
  22196. return Light;
  22197. }(BABYLON.Node));
  22198. BABYLON.Light = Light;
  22199. })(BABYLON || (BABYLON = {}));
  22200. //# sourceMappingURL=babylon.light.js.map
  22201. var BABYLON;
  22202. (function (BABYLON) {
  22203. var Camera = /** @class */ (function (_super) {
  22204. __extends(Camera, _super);
  22205. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22206. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22207. var _this = _super.call(this, name, scene) || this;
  22208. /**
  22209. * The vector the camera should consider as up.
  22210. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22211. */
  22212. _this.upVector = BABYLON.Vector3.Up();
  22213. _this.orthoLeft = null;
  22214. _this.orthoRight = null;
  22215. _this.orthoBottom = null;
  22216. _this.orthoTop = null;
  22217. /**
  22218. * FOV is set in Radians. (default is 0.8)
  22219. */
  22220. _this.fov = 0.8;
  22221. _this.minZ = 1;
  22222. _this.maxZ = 10000.0;
  22223. _this.inertia = 0.9;
  22224. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22225. _this.isIntermediate = false;
  22226. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22227. /**
  22228. * Restricts the camera to viewing objects with the same layerMask.
  22229. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22230. */
  22231. _this.layerMask = 0x0FFFFFFF;
  22232. /**
  22233. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22234. */
  22235. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22236. // Camera rig members
  22237. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22238. _this._rigCameras = new Array();
  22239. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22240. _this._skipRendering = false;
  22241. _this.customRenderTargets = new Array();
  22242. // Observables
  22243. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22244. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22245. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22246. _this.onRestoreStateObservable = new BABYLON.Observable();
  22247. // Cache
  22248. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22249. _this._projectionMatrix = new BABYLON.Matrix();
  22250. _this._doNotComputeProjectionMatrix = false;
  22251. _this._worldMatrix = BABYLON.Matrix.Identity();
  22252. _this._postProcesses = new Array();
  22253. _this._transformMatrix = BABYLON.Matrix.Zero();
  22254. _this._activeMeshes = new BABYLON.SmartArray(256);
  22255. _this._globalPosition = BABYLON.Vector3.Zero();
  22256. _this._refreshFrustumPlanes = true;
  22257. _this.getScene().addCamera(_this);
  22258. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22259. _this.getScene().activeCamera = _this;
  22260. }
  22261. _this.position = position;
  22262. return _this;
  22263. }
  22264. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22265. get: function () {
  22266. return Camera._PERSPECTIVE_CAMERA;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22272. get: function () {
  22273. return Camera._ORTHOGRAPHIC_CAMERA;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22279. /**
  22280. * This is the default FOV mode for perspective cameras.
  22281. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22282. *
  22283. */
  22284. get: function () {
  22285. return Camera._FOVMODE_VERTICAL_FIXED;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22291. /**
  22292. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22293. *
  22294. */
  22295. get: function () {
  22296. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22302. get: function () {
  22303. return Camera._RIG_MODE_NONE;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22309. get: function () {
  22310. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22311. },
  22312. enumerable: true,
  22313. configurable: true
  22314. });
  22315. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22316. get: function () {
  22317. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22323. get: function () {
  22324. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22330. get: function () {
  22331. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22337. get: function () {
  22338. return Camera._RIG_MODE_VR;
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22344. get: function () {
  22345. return Camera._RIG_MODE_WEBVR;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. /**
  22351. * Store current camera state (fov, position, etc..)
  22352. */
  22353. Camera.prototype.storeState = function () {
  22354. this._stateStored = true;
  22355. this._storedFov = this.fov;
  22356. return this;
  22357. };
  22358. /**
  22359. * Restores the camera state values if it has been stored. You must call storeState() first
  22360. */
  22361. Camera.prototype._restoreStateValues = function () {
  22362. if (!this._stateStored) {
  22363. return false;
  22364. }
  22365. this.fov = this._storedFov;
  22366. return true;
  22367. };
  22368. /**
  22369. * Restored camera state. You must call storeState() first
  22370. */
  22371. Camera.prototype.restoreState = function () {
  22372. if (this._restoreStateValues()) {
  22373. this.onRestoreStateObservable.notifyObservers(this);
  22374. return true;
  22375. }
  22376. return false;
  22377. };
  22378. Camera.prototype.getClassName = function () {
  22379. return "Camera";
  22380. };
  22381. /**
  22382. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22383. */
  22384. Camera.prototype.toString = function (fullDetails) {
  22385. var ret = "Name: " + this.name;
  22386. ret += ", type: " + this.getClassName();
  22387. if (this.animations) {
  22388. for (var i = 0; i < this.animations.length; i++) {
  22389. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22390. }
  22391. }
  22392. if (fullDetails) {
  22393. }
  22394. return ret;
  22395. };
  22396. Object.defineProperty(Camera.prototype, "globalPosition", {
  22397. get: function () {
  22398. return this._globalPosition;
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. Camera.prototype.getActiveMeshes = function () {
  22404. return this._activeMeshes;
  22405. };
  22406. Camera.prototype.isActiveMesh = function (mesh) {
  22407. return (this._activeMeshes.indexOf(mesh) !== -1);
  22408. };
  22409. /**
  22410. * Is this camera ready to be used/rendered
  22411. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22412. * @return true if the camera is ready
  22413. */
  22414. Camera.prototype.isReady = function (completeCheck) {
  22415. if (completeCheck === void 0) { completeCheck = false; }
  22416. if (completeCheck) {
  22417. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22418. var pp = _a[_i];
  22419. if (pp && !pp.isReady()) {
  22420. return false;
  22421. }
  22422. }
  22423. }
  22424. return _super.prototype.isReady.call(this, completeCheck);
  22425. };
  22426. //Cache
  22427. Camera.prototype._initCache = function () {
  22428. _super.prototype._initCache.call(this);
  22429. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22430. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22431. this._cache.mode = undefined;
  22432. this._cache.minZ = undefined;
  22433. this._cache.maxZ = undefined;
  22434. this._cache.fov = undefined;
  22435. this._cache.fovMode = undefined;
  22436. this._cache.aspectRatio = undefined;
  22437. this._cache.orthoLeft = undefined;
  22438. this._cache.orthoRight = undefined;
  22439. this._cache.orthoBottom = undefined;
  22440. this._cache.orthoTop = undefined;
  22441. this._cache.renderWidth = undefined;
  22442. this._cache.renderHeight = undefined;
  22443. };
  22444. Camera.prototype._updateCache = function (ignoreParentClass) {
  22445. if (!ignoreParentClass) {
  22446. _super.prototype._updateCache.call(this);
  22447. }
  22448. this._cache.position.copyFrom(this.position);
  22449. this._cache.upVector.copyFrom(this.upVector);
  22450. };
  22451. // Synchronized
  22452. Camera.prototype._isSynchronized = function () {
  22453. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22454. };
  22455. Camera.prototype._isSynchronizedViewMatrix = function () {
  22456. if (!_super.prototype._isSynchronized.call(this))
  22457. return false;
  22458. return this._cache.position.equals(this.position)
  22459. && this._cache.upVector.equals(this.upVector)
  22460. && this.isSynchronizedWithParent();
  22461. };
  22462. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22463. var check = this._cache.mode === this.mode
  22464. && this._cache.minZ === this.minZ
  22465. && this._cache.maxZ === this.maxZ;
  22466. if (!check) {
  22467. return false;
  22468. }
  22469. var engine = this.getEngine();
  22470. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22471. check = this._cache.fov === this.fov
  22472. && this._cache.fovMode === this.fovMode
  22473. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22474. }
  22475. else {
  22476. check = this._cache.orthoLeft === this.orthoLeft
  22477. && this._cache.orthoRight === this.orthoRight
  22478. && this._cache.orthoBottom === this.orthoBottom
  22479. && this._cache.orthoTop === this.orthoTop
  22480. && this._cache.renderWidth === engine.getRenderWidth()
  22481. && this._cache.renderHeight === engine.getRenderHeight();
  22482. }
  22483. return check;
  22484. };
  22485. // Controls
  22486. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22487. };
  22488. Camera.prototype.detachControl = function (element) {
  22489. };
  22490. Camera.prototype.update = function () {
  22491. this._checkInputs();
  22492. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22493. this._updateRigCameras();
  22494. }
  22495. };
  22496. Camera.prototype._checkInputs = function () {
  22497. this.onAfterCheckInputsObservable.notifyObservers(this);
  22498. };
  22499. Object.defineProperty(Camera.prototype, "rigCameras", {
  22500. get: function () {
  22501. return this._rigCameras;
  22502. },
  22503. enumerable: true,
  22504. configurable: true
  22505. });
  22506. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22507. get: function () {
  22508. return this._rigPostProcess;
  22509. },
  22510. enumerable: true,
  22511. configurable: true
  22512. });
  22513. /**
  22514. * Internal, gets the first post proces.
  22515. * @returns the first post process to be run on this camera.
  22516. */
  22517. Camera.prototype._getFirstPostProcess = function () {
  22518. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22519. if (this._postProcesses[ppIndex] !== null) {
  22520. return this._postProcesses[ppIndex];
  22521. }
  22522. }
  22523. return null;
  22524. };
  22525. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22526. // invalidate framebuffer
  22527. var firstPostProcess = this._getFirstPostProcess();
  22528. if (firstPostProcess) {
  22529. firstPostProcess.markTextureDirty();
  22530. }
  22531. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22532. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22533. var cam = this._rigCameras[i];
  22534. var rigPostProcess = cam._rigPostProcess;
  22535. // for VR rig, there does not have to be a post process
  22536. if (rigPostProcess) {
  22537. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22538. if (isPass) {
  22539. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22540. cam.isIntermediate = this._postProcesses.length === 0;
  22541. }
  22542. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22543. rigPostProcess.markTextureDirty();
  22544. }
  22545. else {
  22546. cam._postProcesses = this._postProcesses.slice(0);
  22547. }
  22548. }
  22549. };
  22550. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22551. if (insertAt === void 0) { insertAt = null; }
  22552. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22553. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22554. return 0;
  22555. }
  22556. if (insertAt == null || insertAt < 0) {
  22557. this._postProcesses.push(postProcess);
  22558. }
  22559. else if (this._postProcesses[insertAt] === null) {
  22560. this._postProcesses[insertAt] = postProcess;
  22561. }
  22562. else {
  22563. this._postProcesses.splice(insertAt, 0, postProcess);
  22564. }
  22565. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22566. return this._postProcesses.indexOf(postProcess);
  22567. };
  22568. Camera.prototype.detachPostProcess = function (postProcess) {
  22569. var idx = this._postProcesses.indexOf(postProcess);
  22570. if (idx !== -1) {
  22571. this._postProcesses[idx] = null;
  22572. }
  22573. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22574. };
  22575. Camera.prototype.getWorldMatrix = function () {
  22576. if (this._isSynchronizedViewMatrix()) {
  22577. return this._worldMatrix;
  22578. }
  22579. // Getting the the view matrix will also compute the world matrix.
  22580. this.getViewMatrix();
  22581. return this._worldMatrix;
  22582. };
  22583. Camera.prototype._getViewMatrix = function () {
  22584. return BABYLON.Matrix.Identity();
  22585. };
  22586. Camera.prototype.getViewMatrix = function (force) {
  22587. if (!force && this._isSynchronizedViewMatrix()) {
  22588. return this._computedViewMatrix;
  22589. }
  22590. this.updateCache();
  22591. this._computedViewMatrix = this._getViewMatrix();
  22592. this._currentRenderId = this.getScene().getRenderId();
  22593. this._childRenderId = this._currentRenderId;
  22594. this._refreshFrustumPlanes = true;
  22595. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22596. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22597. }
  22598. this.onViewMatrixChangedObservable.notifyObservers(this);
  22599. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22600. return this._computedViewMatrix;
  22601. };
  22602. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22603. this._doNotComputeProjectionMatrix = true;
  22604. if (projection !== undefined) {
  22605. this._projectionMatrix = projection;
  22606. }
  22607. };
  22608. ;
  22609. Camera.prototype.unfreezeProjectionMatrix = function () {
  22610. this._doNotComputeProjectionMatrix = false;
  22611. };
  22612. ;
  22613. Camera.prototype.getProjectionMatrix = function (force) {
  22614. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22615. return this._projectionMatrix;
  22616. }
  22617. // Cache
  22618. this._cache.mode = this.mode;
  22619. this._cache.minZ = this.minZ;
  22620. this._cache.maxZ = this.maxZ;
  22621. // Matrix
  22622. this._refreshFrustumPlanes = true;
  22623. var engine = this.getEngine();
  22624. var scene = this.getScene();
  22625. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22626. this._cache.fov = this.fov;
  22627. this._cache.fovMode = this.fovMode;
  22628. this._cache.aspectRatio = engine.getAspectRatio(this);
  22629. if (this.minZ <= 0) {
  22630. this.minZ = 0.1;
  22631. }
  22632. if (scene.useRightHandedSystem) {
  22633. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22634. }
  22635. else {
  22636. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22637. }
  22638. }
  22639. else {
  22640. var halfWidth = engine.getRenderWidth() / 2.0;
  22641. var halfHeight = engine.getRenderHeight() / 2.0;
  22642. if (scene.useRightHandedSystem) {
  22643. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22644. }
  22645. else {
  22646. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22647. }
  22648. this._cache.orthoLeft = this.orthoLeft;
  22649. this._cache.orthoRight = this.orthoRight;
  22650. this._cache.orthoBottom = this.orthoBottom;
  22651. this._cache.orthoTop = this.orthoTop;
  22652. this._cache.renderWidth = engine.getRenderWidth();
  22653. this._cache.renderHeight = engine.getRenderHeight();
  22654. }
  22655. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22656. return this._projectionMatrix;
  22657. };
  22658. Camera.prototype.getTranformationMatrix = function () {
  22659. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22660. return this._transformMatrix;
  22661. };
  22662. Camera.prototype.updateFrustumPlanes = function () {
  22663. if (!this._refreshFrustumPlanes) {
  22664. return;
  22665. }
  22666. this.getTranformationMatrix();
  22667. if (!this._frustumPlanes) {
  22668. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22669. }
  22670. else {
  22671. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22672. }
  22673. this._refreshFrustumPlanes = false;
  22674. };
  22675. Camera.prototype.isInFrustum = function (target) {
  22676. this.updateFrustumPlanes();
  22677. return target.isInFrustum(this._frustumPlanes);
  22678. };
  22679. Camera.prototype.isCompletelyInFrustum = function (target) {
  22680. this.updateFrustumPlanes();
  22681. return target.isCompletelyInFrustum(this._frustumPlanes);
  22682. };
  22683. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22684. if (length === void 0) { length = 100; }
  22685. if (!transform) {
  22686. transform = this.getWorldMatrix();
  22687. }
  22688. if (!origin) {
  22689. origin = this.position;
  22690. }
  22691. var forward = new BABYLON.Vector3(0, 0, 1);
  22692. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22693. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22694. return new BABYLON.Ray(origin, direction, length);
  22695. };
  22696. /**
  22697. * Releases resources associated with this node.
  22698. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22699. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22700. */
  22701. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22702. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22703. // Observables
  22704. this.onViewMatrixChangedObservable.clear();
  22705. this.onProjectionMatrixChangedObservable.clear();
  22706. this.onAfterCheckInputsObservable.clear();
  22707. this.onRestoreStateObservable.clear();
  22708. // Inputs
  22709. if (this.inputs) {
  22710. this.inputs.clear();
  22711. }
  22712. // Animations
  22713. this.getScene().stopAnimation(this);
  22714. // Remove from scene
  22715. this.getScene().removeCamera(this);
  22716. while (this._rigCameras.length > 0) {
  22717. var camera = this._rigCameras.pop();
  22718. if (camera) {
  22719. camera.dispose();
  22720. }
  22721. }
  22722. // Postprocesses
  22723. if (this._rigPostProcess) {
  22724. this._rigPostProcess.dispose(this);
  22725. this._rigPostProcess = null;
  22726. this._postProcesses = [];
  22727. }
  22728. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22729. this._rigPostProcess = null;
  22730. this._postProcesses = [];
  22731. }
  22732. else {
  22733. var i = this._postProcesses.length;
  22734. while (--i >= 0) {
  22735. var postProcess = this._postProcesses[i];
  22736. if (postProcess) {
  22737. postProcess.dispose(this);
  22738. }
  22739. }
  22740. }
  22741. // Render targets
  22742. var i = this.customRenderTargets.length;
  22743. while (--i >= 0) {
  22744. this.customRenderTargets[i].dispose();
  22745. }
  22746. this.customRenderTargets = [];
  22747. // Active Meshes
  22748. this._activeMeshes.dispose();
  22749. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22750. };
  22751. Object.defineProperty(Camera.prototype, "leftCamera", {
  22752. // ---- Camera rigs section ----
  22753. get: function () {
  22754. if (this._rigCameras.length < 1) {
  22755. return null;
  22756. }
  22757. return this._rigCameras[0];
  22758. },
  22759. enumerable: true,
  22760. configurable: true
  22761. });
  22762. Object.defineProperty(Camera.prototype, "rightCamera", {
  22763. get: function () {
  22764. if (this._rigCameras.length < 2) {
  22765. return null;
  22766. }
  22767. return this._rigCameras[1];
  22768. },
  22769. enumerable: true,
  22770. configurable: true
  22771. });
  22772. Camera.prototype.getLeftTarget = function () {
  22773. if (this._rigCameras.length < 1) {
  22774. return null;
  22775. }
  22776. return this._rigCameras[0].getTarget();
  22777. };
  22778. Camera.prototype.getRightTarget = function () {
  22779. if (this._rigCameras.length < 2) {
  22780. return null;
  22781. }
  22782. return this._rigCameras[1].getTarget();
  22783. };
  22784. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22785. if (this.cameraRigMode === mode) {
  22786. return;
  22787. }
  22788. while (this._rigCameras.length > 0) {
  22789. var camera = this._rigCameras.pop();
  22790. if (camera) {
  22791. camera.dispose();
  22792. }
  22793. }
  22794. this.cameraRigMode = mode;
  22795. this._cameraRigParams = {};
  22796. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22797. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22798. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22799. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22800. // create the rig cameras, unless none
  22801. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22802. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22803. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22804. if (leftCamera && rightCamera) {
  22805. this._rigCameras.push(leftCamera);
  22806. this._rigCameras.push(rightCamera);
  22807. }
  22808. }
  22809. switch (this.cameraRigMode) {
  22810. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22811. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22812. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22813. break;
  22814. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22815. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22816. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22817. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22818. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22819. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22820. break;
  22821. case Camera.RIG_MODE_VR:
  22822. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22823. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22824. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22825. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22826. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22827. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22828. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22829. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22830. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22831. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22832. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22833. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22834. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22835. if (metrics.compensateDistortion) {
  22836. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22837. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22838. }
  22839. break;
  22840. case Camera.RIG_MODE_WEBVR:
  22841. if (rigParams.vrDisplay) {
  22842. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22843. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22844. //Left eye
  22845. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22846. this._rigCameras[0].setCameraRigParameter("left", true);
  22847. //leaving this for future reference
  22848. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22849. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22850. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22851. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22852. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22853. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22854. this._rigCameras[0].parent = this;
  22855. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22856. //Right eye
  22857. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22858. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22859. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22860. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22861. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22862. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22863. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22864. this._rigCameras[1].parent = this;
  22865. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22866. if (Camera.UseAlternateWebVRRendering) {
  22867. this._rigCameras[1]._skipRendering = true;
  22868. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22869. }
  22870. }
  22871. break;
  22872. }
  22873. this._cascadePostProcessesToRigCams();
  22874. this.update();
  22875. };
  22876. Camera.prototype._getVRProjectionMatrix = function () {
  22877. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22878. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22879. return this._projectionMatrix;
  22880. };
  22881. Camera.prototype._updateCameraRotationMatrix = function () {
  22882. //Here for WebVR
  22883. };
  22884. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22885. //Here for WebVR
  22886. };
  22887. /**
  22888. * This function MUST be overwritten by the different WebVR cameras available.
  22889. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22890. */
  22891. Camera.prototype._getWebVRProjectionMatrix = function () {
  22892. return BABYLON.Matrix.Identity();
  22893. };
  22894. /**
  22895. * This function MUST be overwritten by the different WebVR cameras available.
  22896. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22897. */
  22898. Camera.prototype._getWebVRViewMatrix = function () {
  22899. return BABYLON.Matrix.Identity();
  22900. };
  22901. Camera.prototype.setCameraRigParameter = function (name, value) {
  22902. if (!this._cameraRigParams) {
  22903. this._cameraRigParams = {};
  22904. }
  22905. this._cameraRigParams[name] = value;
  22906. //provisionnally:
  22907. if (name === "interaxialDistance") {
  22908. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22909. }
  22910. };
  22911. /**
  22912. * needs to be overridden by children so sub has required properties to be copied
  22913. */
  22914. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22915. return null;
  22916. };
  22917. /**
  22918. * May need to be overridden by children
  22919. */
  22920. Camera.prototype._updateRigCameras = function () {
  22921. for (var i = 0; i < this._rigCameras.length; i++) {
  22922. this._rigCameras[i].minZ = this.minZ;
  22923. this._rigCameras[i].maxZ = this.maxZ;
  22924. this._rigCameras[i].fov = this.fov;
  22925. }
  22926. // only update viewport when ANAGLYPH
  22927. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22928. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22929. }
  22930. };
  22931. Camera.prototype._setupInputs = function () {
  22932. };
  22933. Camera.prototype.serialize = function () {
  22934. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22935. // Type
  22936. serializationObject.type = this.getClassName();
  22937. // Parent
  22938. if (this.parent) {
  22939. serializationObject.parentId = this.parent.id;
  22940. }
  22941. if (this.inputs) {
  22942. this.inputs.serialize(serializationObject);
  22943. }
  22944. // Animations
  22945. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22946. serializationObject.ranges = this.serializeAnimationRanges();
  22947. return serializationObject;
  22948. };
  22949. Camera.prototype.clone = function (name) {
  22950. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22951. };
  22952. Camera.prototype.getDirection = function (localAxis) {
  22953. var result = BABYLON.Vector3.Zero();
  22954. this.getDirectionToRef(localAxis, result);
  22955. return result;
  22956. };
  22957. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22958. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22959. };
  22960. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22961. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22962. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22963. switch (type) {
  22964. case "ArcRotateCamera":
  22965. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22966. case "DeviceOrientationCamera":
  22967. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22968. case "FollowCamera":
  22969. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22970. case "ArcFollowCamera":
  22971. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22972. case "GamepadCamera":
  22973. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22974. case "TouchCamera":
  22975. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22976. case "VirtualJoysticksCamera":
  22977. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22978. case "WebVRFreeCamera":
  22979. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22980. case "WebVRGamepadCamera":
  22981. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22982. case "VRDeviceOrientationFreeCamera":
  22983. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22984. case "VRDeviceOrientationGamepadCamera":
  22985. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22986. case "AnaglyphArcRotateCamera":
  22987. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22988. case "AnaglyphFreeCamera":
  22989. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22990. case "AnaglyphGamepadCamera":
  22991. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22992. case "AnaglyphUniversalCamera":
  22993. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22994. case "StereoscopicArcRotateCamera":
  22995. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22996. case "StereoscopicFreeCamera":
  22997. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22998. case "StereoscopicGamepadCamera":
  22999. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23000. case "StereoscopicUniversalCamera":
  23001. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23002. case "FreeCamera": // Forcing Universal here
  23003. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23004. default: // Universal Camera is the default value
  23005. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23006. }
  23007. };
  23008. Camera.prototype.computeWorldMatrix = function () {
  23009. return this.getWorldMatrix();
  23010. };
  23011. Camera.Parse = function (parsedCamera, scene) {
  23012. var type = parsedCamera.type;
  23013. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23014. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23015. // Parent
  23016. if (parsedCamera.parentId) {
  23017. camera._waitingParentId = parsedCamera.parentId;
  23018. }
  23019. //If camera has an input manager, let it parse inputs settings
  23020. if (camera.inputs) {
  23021. camera.inputs.parse(parsedCamera);
  23022. camera._setupInputs();
  23023. }
  23024. if (camera.setPosition) { // need to force position
  23025. camera.position.copyFromFloats(0, 0, 0);
  23026. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23027. }
  23028. // Target
  23029. if (parsedCamera.target) {
  23030. if (camera.setTarget) {
  23031. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23032. }
  23033. }
  23034. // Apply 3d rig, when found
  23035. if (parsedCamera.cameraRigMode) {
  23036. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23037. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23038. }
  23039. // Animations
  23040. if (parsedCamera.animations) {
  23041. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23042. var parsedAnimation = parsedCamera.animations[animationIndex];
  23043. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23044. }
  23045. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23046. }
  23047. if (parsedCamera.autoAnimate) {
  23048. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23049. }
  23050. return camera;
  23051. };
  23052. // Statics
  23053. Camera._PERSPECTIVE_CAMERA = 0;
  23054. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23055. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23056. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23057. Camera._RIG_MODE_NONE = 0;
  23058. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23059. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23060. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23061. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23062. Camera._RIG_MODE_VR = 20;
  23063. Camera._RIG_MODE_WEBVR = 21;
  23064. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23065. Camera.UseAlternateWebVRRendering = false;
  23066. __decorate([
  23067. BABYLON.serializeAsVector3()
  23068. ], Camera.prototype, "position", void 0);
  23069. __decorate([
  23070. BABYLON.serializeAsVector3()
  23071. ], Camera.prototype, "upVector", void 0);
  23072. __decorate([
  23073. BABYLON.serialize()
  23074. ], Camera.prototype, "orthoLeft", void 0);
  23075. __decorate([
  23076. BABYLON.serialize()
  23077. ], Camera.prototype, "orthoRight", void 0);
  23078. __decorate([
  23079. BABYLON.serialize()
  23080. ], Camera.prototype, "orthoBottom", void 0);
  23081. __decorate([
  23082. BABYLON.serialize()
  23083. ], Camera.prototype, "orthoTop", void 0);
  23084. __decorate([
  23085. BABYLON.serialize()
  23086. ], Camera.prototype, "fov", void 0);
  23087. __decorate([
  23088. BABYLON.serialize()
  23089. ], Camera.prototype, "minZ", void 0);
  23090. __decorate([
  23091. BABYLON.serialize()
  23092. ], Camera.prototype, "maxZ", void 0);
  23093. __decorate([
  23094. BABYLON.serialize()
  23095. ], Camera.prototype, "inertia", void 0);
  23096. __decorate([
  23097. BABYLON.serialize()
  23098. ], Camera.prototype, "mode", void 0);
  23099. __decorate([
  23100. BABYLON.serialize()
  23101. ], Camera.prototype, "layerMask", void 0);
  23102. __decorate([
  23103. BABYLON.serialize()
  23104. ], Camera.prototype, "fovMode", void 0);
  23105. __decorate([
  23106. BABYLON.serialize()
  23107. ], Camera.prototype, "cameraRigMode", void 0);
  23108. __decorate([
  23109. BABYLON.serialize()
  23110. ], Camera.prototype, "interaxialDistance", void 0);
  23111. __decorate([
  23112. BABYLON.serialize()
  23113. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23114. return Camera;
  23115. }(BABYLON.Node));
  23116. BABYLON.Camera = Camera;
  23117. })(BABYLON || (BABYLON = {}));
  23118. //# sourceMappingURL=babylon.camera.js.map
  23119. var BABYLON;
  23120. (function (BABYLON) {
  23121. var RenderingManager = /** @class */ (function () {
  23122. function RenderingManager(scene) {
  23123. this._renderingGroups = new Array();
  23124. this._autoClearDepthStencil = {};
  23125. this._customOpaqueSortCompareFn = {};
  23126. this._customAlphaTestSortCompareFn = {};
  23127. this._customTransparentSortCompareFn = {};
  23128. this._renderinGroupInfo = null;
  23129. this._scene = scene;
  23130. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23131. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23132. }
  23133. }
  23134. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23135. if (depth === void 0) { depth = true; }
  23136. if (stencil === void 0) { stencil = true; }
  23137. if (this._depthStencilBufferAlreadyCleaned) {
  23138. return;
  23139. }
  23140. this._scene.getEngine().clear(null, false, depth, stencil);
  23141. this._depthStencilBufferAlreadyCleaned = true;
  23142. };
  23143. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23144. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23145. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23146. var info = null;
  23147. if (observable) {
  23148. if (!this._renderinGroupInfo) {
  23149. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23150. }
  23151. info = this._renderinGroupInfo;
  23152. info.scene = this._scene;
  23153. info.camera = this._scene.activeCamera;
  23154. }
  23155. // Dispatch sprites
  23156. if (renderSprites) {
  23157. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23158. var manager = this._scene.spriteManagers[index];
  23159. this.dispatchSprites(manager);
  23160. }
  23161. }
  23162. // Render
  23163. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23164. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23165. var renderingGroup = this._renderingGroups[index];
  23166. if (!renderingGroup && !observable)
  23167. continue;
  23168. var renderingGroupMask = 0;
  23169. // Fire PRECLEAR stage
  23170. if (observable && info) {
  23171. renderingGroupMask = Math.pow(2, index);
  23172. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23173. info.renderingGroupId = index;
  23174. observable.notifyObservers(info, renderingGroupMask);
  23175. }
  23176. // Clear depth/stencil if needed
  23177. if (RenderingManager.AUTOCLEAR) {
  23178. var autoClear = this._autoClearDepthStencil[index];
  23179. if (autoClear && autoClear.autoClear) {
  23180. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23181. }
  23182. }
  23183. if (observable && info) {
  23184. // Fire PREOPAQUE stage
  23185. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23186. observable.notifyObservers(info, renderingGroupMask);
  23187. // Fire PRETRANSPARENT stage
  23188. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23189. observable.notifyObservers(info, renderingGroupMask);
  23190. }
  23191. if (renderingGroup)
  23192. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23193. // Fire POSTTRANSPARENT stage
  23194. if (observable && info) {
  23195. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23196. observable.notifyObservers(info, renderingGroupMask);
  23197. }
  23198. }
  23199. };
  23200. RenderingManager.prototype.reset = function () {
  23201. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23202. var renderingGroup = this._renderingGroups[index];
  23203. if (renderingGroup) {
  23204. renderingGroup.prepare();
  23205. }
  23206. }
  23207. };
  23208. RenderingManager.prototype.dispose = function () {
  23209. this.freeRenderingGroups();
  23210. this._renderingGroups.length = 0;
  23211. };
  23212. /**
  23213. * Clear the info related to rendering groups preventing retention points during dispose.
  23214. */
  23215. RenderingManager.prototype.freeRenderingGroups = function () {
  23216. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23217. var renderingGroup = this._renderingGroups[index];
  23218. if (renderingGroup) {
  23219. renderingGroup.dispose();
  23220. }
  23221. }
  23222. };
  23223. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23224. if (this._renderingGroups[renderingGroupId] === undefined) {
  23225. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23226. }
  23227. };
  23228. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23229. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23230. this._prepareRenderingGroup(renderingGroupId);
  23231. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23232. };
  23233. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23234. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23235. this._prepareRenderingGroup(renderingGroupId);
  23236. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23237. };
  23238. /**
  23239. * @param subMesh The submesh to dispatch
  23240. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23241. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23242. */
  23243. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23244. if (mesh === undefined) {
  23245. mesh = subMesh.getMesh();
  23246. }
  23247. var renderingGroupId = mesh.renderingGroupId || 0;
  23248. this._prepareRenderingGroup(renderingGroupId);
  23249. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23250. };
  23251. /**
  23252. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23253. * This allowed control for front to back rendering or reversly depending of the special needs.
  23254. *
  23255. * @param renderingGroupId The rendering group id corresponding to its index
  23256. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23257. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23258. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23259. */
  23260. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23261. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23262. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23263. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23264. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23265. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23266. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23267. if (this._renderingGroups[renderingGroupId]) {
  23268. var group = this._renderingGroups[renderingGroupId];
  23269. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23270. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23271. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23272. }
  23273. };
  23274. /**
  23275. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23276. *
  23277. * @param renderingGroupId The rendering group id corresponding to its index
  23278. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23279. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23280. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23281. */
  23282. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23283. if (depth === void 0) { depth = true; }
  23284. if (stencil === void 0) { stencil = true; }
  23285. this._autoClearDepthStencil[renderingGroupId] = {
  23286. autoClear: autoClearDepthStencil,
  23287. depth: depth,
  23288. stencil: stencil
  23289. };
  23290. };
  23291. /**
  23292. * The max id used for rendering groups (not included)
  23293. */
  23294. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23295. /**
  23296. * The min id used for rendering groups (included)
  23297. */
  23298. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23299. /**
  23300. * Used to globally prevent autoclearing scenes.
  23301. */
  23302. RenderingManager.AUTOCLEAR = true;
  23303. return RenderingManager;
  23304. }());
  23305. BABYLON.RenderingManager = RenderingManager;
  23306. })(BABYLON || (BABYLON = {}));
  23307. //# sourceMappingURL=babylon.renderingManager.js.map
  23308. var BABYLON;
  23309. (function (BABYLON) {
  23310. var RenderingGroup = /** @class */ (function () {
  23311. /**
  23312. * Creates a new rendering group.
  23313. * @param index The rendering group index
  23314. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23315. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23316. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23317. */
  23318. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23319. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23320. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23321. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23322. this.index = index;
  23323. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23324. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23325. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23326. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23327. this._particleSystems = new BABYLON.SmartArray(256);
  23328. this._spriteManagers = new BABYLON.SmartArray(256);
  23329. this._edgesRenderers = new BABYLON.SmartArray(16);
  23330. this._scene = scene;
  23331. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23332. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23333. this.transparentSortCompareFn = transparentSortCompareFn;
  23334. }
  23335. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23336. /**
  23337. * Set the opaque sort comparison function.
  23338. * If null the sub meshes will be render in the order they were created
  23339. */
  23340. set: function (value) {
  23341. this._opaqueSortCompareFn = value;
  23342. if (value) {
  23343. this._renderOpaque = this.renderOpaqueSorted;
  23344. }
  23345. else {
  23346. this._renderOpaque = RenderingGroup.renderUnsorted;
  23347. }
  23348. },
  23349. enumerable: true,
  23350. configurable: true
  23351. });
  23352. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23353. /**
  23354. * Set the alpha test sort comparison function.
  23355. * If null the sub meshes will be render in the order they were created
  23356. */
  23357. set: function (value) {
  23358. this._alphaTestSortCompareFn = value;
  23359. if (value) {
  23360. this._renderAlphaTest = this.renderAlphaTestSorted;
  23361. }
  23362. else {
  23363. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23364. }
  23365. },
  23366. enumerable: true,
  23367. configurable: true
  23368. });
  23369. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23370. /**
  23371. * Set the transparent sort comparison function.
  23372. * If null the sub meshes will be render in the order they were created
  23373. */
  23374. set: function (value) {
  23375. if (value) {
  23376. this._transparentSortCompareFn = value;
  23377. }
  23378. else {
  23379. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23380. }
  23381. this._renderTransparent = this.renderTransparentSorted;
  23382. },
  23383. enumerable: true,
  23384. configurable: true
  23385. });
  23386. /**
  23387. * Render all the sub meshes contained in the group.
  23388. * @param customRenderFunction Used to override the default render behaviour of the group.
  23389. * @returns true if rendered some submeshes.
  23390. */
  23391. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23392. if (customRenderFunction) {
  23393. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23394. return;
  23395. }
  23396. var engine = this._scene.getEngine();
  23397. // Depth only
  23398. if (this._depthOnlySubMeshes.length !== 0) {
  23399. engine.setColorWrite(false);
  23400. this._renderAlphaTest(this._depthOnlySubMeshes);
  23401. engine.setColorWrite(true);
  23402. }
  23403. // Opaque
  23404. if (this._opaqueSubMeshes.length !== 0) {
  23405. this._renderOpaque(this._opaqueSubMeshes);
  23406. }
  23407. // Alpha test
  23408. if (this._alphaTestSubMeshes.length !== 0) {
  23409. this._renderAlphaTest(this._alphaTestSubMeshes);
  23410. }
  23411. var stencilState = engine.getStencilBuffer();
  23412. engine.setStencilBuffer(false);
  23413. // Sprites
  23414. if (renderSprites) {
  23415. this._renderSprites();
  23416. }
  23417. // Particles
  23418. if (renderParticles) {
  23419. this._renderParticles(activeMeshes);
  23420. }
  23421. if (this.onBeforeTransparentRendering) {
  23422. this.onBeforeTransparentRendering();
  23423. }
  23424. // Transparent
  23425. if (this._transparentSubMeshes.length !== 0) {
  23426. this._renderTransparent(this._transparentSubMeshes);
  23427. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23428. }
  23429. // Set back stencil to false in case it changes before the edge renderer.
  23430. engine.setStencilBuffer(false);
  23431. // Edges
  23432. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23433. this._edgesRenderers.data[edgesRendererIndex].render();
  23434. }
  23435. // Restore Stencil state.
  23436. engine.setStencilBuffer(stencilState);
  23437. };
  23438. /**
  23439. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23440. * @param subMeshes The submeshes to render
  23441. */
  23442. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23443. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23444. };
  23445. /**
  23446. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23447. * @param subMeshes The submeshes to render
  23448. */
  23449. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23450. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23451. };
  23452. /**
  23453. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23454. * @param subMeshes The submeshes to render
  23455. */
  23456. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23457. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23458. };
  23459. /**
  23460. * Renders the submeshes in a specified order.
  23461. * @param subMeshes The submeshes to sort before render
  23462. * @param sortCompareFn The comparison function use to sort
  23463. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23464. * @param transparent Specifies to activate blending if true
  23465. */
  23466. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23467. var subIndex = 0;
  23468. var subMesh;
  23469. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23470. for (; subIndex < subMeshes.length; subIndex++) {
  23471. subMesh = subMeshes.data[subIndex];
  23472. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23473. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23474. }
  23475. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23476. if (sortCompareFn) {
  23477. sortedArray.sort(sortCompareFn);
  23478. }
  23479. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23480. subMesh = sortedArray[subIndex];
  23481. if (transparent) {
  23482. var material = subMesh.getMaterial();
  23483. if (material && material.needDepthPrePass) {
  23484. var engine = material.getScene().getEngine();
  23485. engine.setColorWrite(false);
  23486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23487. subMesh.render(false);
  23488. engine.setColorWrite(true);
  23489. }
  23490. }
  23491. subMesh.render(transparent);
  23492. }
  23493. };
  23494. /**
  23495. * Renders the submeshes in the order they were dispatched (no sort applied).
  23496. * @param subMeshes The submeshes to render
  23497. */
  23498. RenderingGroup.renderUnsorted = function (subMeshes) {
  23499. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23500. var submesh = subMeshes.data[subIndex];
  23501. submesh.render(false);
  23502. }
  23503. };
  23504. /**
  23505. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23506. * are rendered back to front if in the same alpha index.
  23507. *
  23508. * @param a The first submesh
  23509. * @param b The second submesh
  23510. * @returns The result of the comparison
  23511. */
  23512. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23513. // Alpha index first
  23514. if (a._alphaIndex > b._alphaIndex) {
  23515. return 1;
  23516. }
  23517. if (a._alphaIndex < b._alphaIndex) {
  23518. return -1;
  23519. }
  23520. // Then distance to camera
  23521. return RenderingGroup.backToFrontSortCompare(a, b);
  23522. };
  23523. /**
  23524. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23525. * are rendered back to front.
  23526. *
  23527. * @param a The first submesh
  23528. * @param b The second submesh
  23529. * @returns The result of the comparison
  23530. */
  23531. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23532. // Then distance to camera
  23533. if (a._distanceToCamera < b._distanceToCamera) {
  23534. return 1;
  23535. }
  23536. if (a._distanceToCamera > b._distanceToCamera) {
  23537. return -1;
  23538. }
  23539. return 0;
  23540. };
  23541. /**
  23542. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23543. * are rendered front to back (prevent overdraw).
  23544. *
  23545. * @param a The first submesh
  23546. * @param b The second submesh
  23547. * @returns The result of the comparison
  23548. */
  23549. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23550. // Then distance to camera
  23551. if (a._distanceToCamera < b._distanceToCamera) {
  23552. return -1;
  23553. }
  23554. if (a._distanceToCamera > b._distanceToCamera) {
  23555. return 1;
  23556. }
  23557. return 0;
  23558. };
  23559. /**
  23560. * Resets the different lists of submeshes to prepare a new frame.
  23561. */
  23562. RenderingGroup.prototype.prepare = function () {
  23563. this._opaqueSubMeshes.reset();
  23564. this._transparentSubMeshes.reset();
  23565. this._alphaTestSubMeshes.reset();
  23566. this._depthOnlySubMeshes.reset();
  23567. this._particleSystems.reset();
  23568. this._spriteManagers.reset();
  23569. this._edgesRenderers.reset();
  23570. };
  23571. RenderingGroup.prototype.dispose = function () {
  23572. this._opaqueSubMeshes.dispose();
  23573. this._transparentSubMeshes.dispose();
  23574. this._alphaTestSubMeshes.dispose();
  23575. this._depthOnlySubMeshes.dispose();
  23576. this._particleSystems.dispose();
  23577. this._spriteManagers.dispose();
  23578. this._edgesRenderers.dispose();
  23579. };
  23580. /**
  23581. * Inserts the submesh in its correct queue depending on its material.
  23582. * @param subMesh The submesh to dispatch
  23583. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23584. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23585. */
  23586. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23587. // Get mesh and materials if not provided
  23588. if (mesh === undefined) {
  23589. mesh = subMesh.getMesh();
  23590. }
  23591. if (material === undefined) {
  23592. material = subMesh.getMaterial();
  23593. }
  23594. if (material === null || material === undefined) {
  23595. return;
  23596. }
  23597. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23598. this._transparentSubMeshes.push(subMesh);
  23599. }
  23600. else if (material.needAlphaTesting()) { // Alpha test
  23601. if (material.needDepthPrePass) {
  23602. this._depthOnlySubMeshes.push(subMesh);
  23603. }
  23604. this._alphaTestSubMeshes.push(subMesh);
  23605. }
  23606. else {
  23607. if (material.needDepthPrePass) {
  23608. this._depthOnlySubMeshes.push(subMesh);
  23609. }
  23610. this._opaqueSubMeshes.push(subMesh); // Opaque
  23611. }
  23612. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23613. this._edgesRenderers.push(mesh._edgesRenderer);
  23614. }
  23615. };
  23616. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23617. this._spriteManagers.push(spriteManager);
  23618. };
  23619. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23620. this._particleSystems.push(particleSystem);
  23621. };
  23622. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23623. if (this._particleSystems.length === 0) {
  23624. return;
  23625. }
  23626. // Particles
  23627. var activeCamera = this._scene.activeCamera;
  23628. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23629. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23630. var particleSystem = this._particleSystems.data[particleIndex];
  23631. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23632. continue;
  23633. }
  23634. var emitter = particleSystem.emitter;
  23635. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23636. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23637. }
  23638. }
  23639. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23640. };
  23641. RenderingGroup.prototype._renderSprites = function () {
  23642. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23643. return;
  23644. }
  23645. // Sprites
  23646. var activeCamera = this._scene.activeCamera;
  23647. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23648. for (var id = 0; id < this._spriteManagers.length; id++) {
  23649. var spriteManager = this._spriteManagers.data[id];
  23650. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23651. spriteManager.render();
  23652. }
  23653. }
  23654. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23655. };
  23656. return RenderingGroup;
  23657. }());
  23658. BABYLON.RenderingGroup = RenderingGroup;
  23659. })(BABYLON || (BABYLON = {}));
  23660. //# sourceMappingURL=babylon.renderingGroup.js.map
  23661. var BABYLON;
  23662. (function (BABYLON) {
  23663. /** @hidden */
  23664. var ClickInfo = /** @class */ (function () {
  23665. function ClickInfo() {
  23666. this._singleClick = false;
  23667. this._doubleClick = false;
  23668. this._hasSwiped = false;
  23669. this._ignore = false;
  23670. }
  23671. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23672. get: function () {
  23673. return this._singleClick;
  23674. },
  23675. set: function (b) {
  23676. this._singleClick = b;
  23677. },
  23678. enumerable: true,
  23679. configurable: true
  23680. });
  23681. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23682. get: function () {
  23683. return this._doubleClick;
  23684. },
  23685. set: function (b) {
  23686. this._doubleClick = b;
  23687. },
  23688. enumerable: true,
  23689. configurable: true
  23690. });
  23691. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23692. get: function () {
  23693. return this._hasSwiped;
  23694. },
  23695. set: function (b) {
  23696. this._hasSwiped = b;
  23697. },
  23698. enumerable: true,
  23699. configurable: true
  23700. });
  23701. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23702. get: function () {
  23703. return this._ignore;
  23704. },
  23705. set: function (b) {
  23706. this._ignore = b;
  23707. },
  23708. enumerable: true,
  23709. configurable: true
  23710. });
  23711. return ClickInfo;
  23712. }());
  23713. /**
  23714. * This class is used by the onRenderingGroupObservable
  23715. */
  23716. var RenderingGroupInfo = /** @class */ (function () {
  23717. function RenderingGroupInfo() {
  23718. }
  23719. /**
  23720. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23721. * This stage will be fired no matter what
  23722. */
  23723. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23724. /**
  23725. * Called before opaque object are rendered.
  23726. * This stage will be fired only if there's 3D Opaque content to render
  23727. */
  23728. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23729. /**
  23730. * Called after the opaque objects are rendered and before the transparent ones
  23731. * This stage will be fired only if there's 3D transparent content to render
  23732. */
  23733. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23734. /**
  23735. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23736. * This stage will be fired no matter what
  23737. */
  23738. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23739. return RenderingGroupInfo;
  23740. }());
  23741. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23742. /**
  23743. * Represents a scene to be rendered by the engine.
  23744. * @see http://doc.babylonjs.com/features/scene
  23745. */
  23746. var Scene = /** @class */ (function () {
  23747. /**
  23748. * Creates a new Scene
  23749. * @param engine defines the engine to use to render this scene
  23750. */
  23751. function Scene(engine) {
  23752. // Members
  23753. /**
  23754. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23755. */
  23756. this.autoClear = true;
  23757. /**
  23758. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23759. */
  23760. this.autoClearDepthAndStencil = true;
  23761. /**
  23762. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23763. */
  23764. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23765. /**
  23766. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23767. */
  23768. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23769. this._forceWireframe = false;
  23770. this._forcePointsCloud = false;
  23771. /**
  23772. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23773. */
  23774. this.forceShowBoundingBoxes = false;
  23775. /**
  23776. * Gets or sets a boolean indicating if animations are enabled
  23777. */
  23778. this.animationsEnabled = true;
  23779. this._animationPropertiesOverride = null;
  23780. /**
  23781. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23782. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23783. */
  23784. this.useConstantAnimationDeltaTime = false;
  23785. /**
  23786. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23787. * Please note that it requires to run a ray cast through the scene on every frame
  23788. */
  23789. this.constantlyUpdateMeshUnderPointer = false;
  23790. /**
  23791. * Defines the HTML cursor to use when hovering over interactive elements
  23792. */
  23793. this.hoverCursor = "pointer";
  23794. /**
  23795. * Defines the HTML default cursor to use (empty by default)
  23796. */
  23797. this.defaultCursor = "";
  23798. /**
  23799. * This is used to call preventDefault() on pointer down
  23800. * in order to block unwanted artifacts like system double clicks
  23801. */
  23802. this.preventDefaultOnPointerDown = true;
  23803. // Metadata
  23804. /**
  23805. * Gets or sets user defined metadata
  23806. */
  23807. this.metadata = null;
  23808. /**
  23809. * Use this array to add regular expressions used to disable offline support for specific urls
  23810. */
  23811. this.disableOfflineSupportExceptionRules = new Array();
  23812. /**
  23813. * An event triggered when the scene is disposed.
  23814. */
  23815. this.onDisposeObservable = new BABYLON.Observable();
  23816. this._onDisposeObserver = null;
  23817. /**
  23818. * An event triggered before rendering the scene (right after animations and physics)
  23819. */
  23820. this.onBeforeRenderObservable = new BABYLON.Observable();
  23821. this._onBeforeRenderObserver = null;
  23822. /**
  23823. * An event triggered after rendering the scene
  23824. */
  23825. this.onAfterRenderObservable = new BABYLON.Observable();
  23826. this._onAfterRenderObserver = null;
  23827. /**
  23828. * An event triggered before animating the scene
  23829. */
  23830. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23831. /**
  23832. * An event triggered after animations processing
  23833. */
  23834. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23835. /**
  23836. * An event triggered before draw calls are ready to be sent
  23837. */
  23838. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23839. /**
  23840. * An event triggered after draw calls have been sent
  23841. */
  23842. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23843. /**
  23844. * An event triggered when physic simulation is about to be run
  23845. */
  23846. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23847. /**
  23848. * An event triggered when physic simulation has been done
  23849. */
  23850. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered when the scene is ready
  23853. */
  23854. this.onReadyObservable = new BABYLON.Observable();
  23855. /**
  23856. * An event triggered before rendering a camera
  23857. */
  23858. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23859. this._onBeforeCameraRenderObserver = null;
  23860. /**
  23861. * An event triggered after rendering a camera
  23862. */
  23863. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23864. this._onAfterCameraRenderObserver = null;
  23865. /**
  23866. * An event triggered when active meshes evaluation is about to start
  23867. */
  23868. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23869. /**
  23870. * An event triggered when active meshes evaluation is done
  23871. */
  23872. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23873. /**
  23874. * An event triggered when particles rendering is about to start
  23875. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23876. */
  23877. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23878. /**
  23879. * An event triggered when particles rendering is done
  23880. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23881. */
  23882. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23883. /**
  23884. * An event triggered when sprites rendering is about to start
  23885. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23886. */
  23887. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23888. /**
  23889. * An event triggered when sprites rendering is done
  23890. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23891. */
  23892. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23893. /**
  23894. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23895. */
  23896. this.onDataLoadedObservable = new BABYLON.Observable();
  23897. /**
  23898. * An event triggered when a camera is created
  23899. */
  23900. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23901. /**
  23902. * An event triggered when a camera is removed
  23903. */
  23904. this.onCameraRemovedObservable = new BABYLON.Observable();
  23905. /**
  23906. * An event triggered when a light is created
  23907. */
  23908. this.onNewLightAddedObservable = new BABYLON.Observable();
  23909. /**
  23910. * An event triggered when a light is removed
  23911. */
  23912. this.onLightRemovedObservable = new BABYLON.Observable();
  23913. /**
  23914. * An event triggered when a geometry is created
  23915. */
  23916. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23917. /**
  23918. * An event triggered when a geometry is removed
  23919. */
  23920. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23921. /**
  23922. * An event triggered when a transform node is created
  23923. */
  23924. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23925. /**
  23926. * An event triggered when a transform node is removed
  23927. */
  23928. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23929. /**
  23930. * An event triggered when a mesh is created
  23931. */
  23932. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23933. /**
  23934. * An event triggered when a mesh is removed
  23935. */
  23936. this.onMeshRemovedObservable = new BABYLON.Observable();
  23937. /**
  23938. * An event triggered when render targets are about to be rendered
  23939. * Can happen multiple times per frame.
  23940. */
  23941. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23942. /**
  23943. * An event triggered when render targets were rendered.
  23944. * Can happen multiple times per frame.
  23945. */
  23946. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23947. /**
  23948. * An event triggered before calculating deterministic simulation step
  23949. */
  23950. this.onBeforeStepObservable = new BABYLON.Observable();
  23951. /**
  23952. * An event triggered after calculating deterministic simulation step
  23953. */
  23954. this.onAfterStepObservable = new BABYLON.Observable();
  23955. /**
  23956. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23957. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23958. * 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)
  23959. */
  23960. this.onRenderingGroupObservable = new BABYLON.Observable();
  23961. // Animations
  23962. /**
  23963. * Gets a list of Animations associated with the scene
  23964. */
  23965. this.animations = [];
  23966. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23967. /**
  23968. * 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).
  23969. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23970. */
  23971. this.onPrePointerObservable = new BABYLON.Observable();
  23972. /**
  23973. * Observable event triggered each time an input event is received from the rendering canvas
  23974. */
  23975. this.onPointerObservable = new BABYLON.Observable();
  23976. this._meshPickProceed = false;
  23977. this._currentPickResult = null;
  23978. this._previousPickResult = null;
  23979. this._totalPointersPressed = 0;
  23980. this._doubleClickOccured = false;
  23981. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23982. this.cameraToUseForPointers = null;
  23983. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23984. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23985. this._startingPointerTime = 0;
  23986. this._previousStartingPointerTime = 0;
  23987. this._pointerCaptures = {};
  23988. // Deterministic lockstep
  23989. this._timeAccumulator = 0;
  23990. this._currentStepId = 0;
  23991. this._currentInternalStep = 0;
  23992. // Keyboard
  23993. /**
  23994. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23995. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23996. */
  23997. this.onPreKeyboardObservable = new BABYLON.Observable();
  23998. /**
  23999. * Observable event triggered each time an keyboard event is received from the hosting window
  24000. */
  24001. this.onKeyboardObservable = new BABYLON.Observable();
  24002. // Coordinates system
  24003. this._useRightHandedSystem = false;
  24004. // Fog
  24005. this._fogEnabled = true;
  24006. this._fogMode = Scene.FOGMODE_NONE;
  24007. /**
  24008. * Gets or sets the fog color to use
  24009. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24010. */
  24011. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24012. /**
  24013. * Gets or sets the fog density to use
  24014. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24015. */
  24016. this.fogDensity = 0.1;
  24017. /**
  24018. * Gets or sets the fog start distance to use
  24019. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24020. */
  24021. this.fogStart = 0;
  24022. /**
  24023. * Gets or sets the fog end distance to use
  24024. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24025. */
  24026. this.fogEnd = 1000.0;
  24027. // Lights
  24028. this._shadowsEnabled = true;
  24029. this._lightsEnabled = true;
  24030. /**
  24031. * All of the lights added to this scene
  24032. * @see http://doc.babylonjs.com/babylon101/lights
  24033. */
  24034. this.lights = new Array();
  24035. // Cameras
  24036. /** All of the cameras added to this scene.
  24037. * @see http://doc.babylonjs.com/babylon101/cameras
  24038. */
  24039. this.cameras = new Array();
  24040. /** All of the active cameras added to this scene. */
  24041. this.activeCameras = new Array();
  24042. // Meshes
  24043. /**
  24044. * All of the tranform nodes added to this scene
  24045. * @see http://doc.babylonjs.com/how_to/transformnode
  24046. */
  24047. this.transformNodes = new Array();
  24048. /**
  24049. * All of the (abstract) meshes added to this scene
  24050. */
  24051. this.meshes = new Array();
  24052. /**
  24053. * All of the animation groups added to this scene
  24054. * @see http://doc.babylonjs.com/how_to/group
  24055. */
  24056. this.animationGroups = new Array();
  24057. // Geometries
  24058. this._geometries = new Array();
  24059. /**
  24060. * All of the materials added to this scene
  24061. * @see http://doc.babylonjs.com/babylon101/materials
  24062. */
  24063. this.materials = new Array();
  24064. /**
  24065. * All of the multi-materials added to this scene
  24066. * @see http://doc.babylonjs.com/how_to/multi_materials
  24067. */
  24068. this.multiMaterials = new Array();
  24069. // Textures
  24070. this._texturesEnabled = true;
  24071. /**
  24072. * All of the textures added to this scene
  24073. */
  24074. this.textures = new Array();
  24075. // Particles
  24076. /**
  24077. * Gets or sets a boolean indicating if particles are enabled on this scene
  24078. */
  24079. this.particlesEnabled = true;
  24080. /**
  24081. * All of the particle systems added to this scene
  24082. * @see http://doc.babylonjs.com/babylon101/particles
  24083. */
  24084. this.particleSystems = new Array();
  24085. // Sprites
  24086. /**
  24087. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24088. */
  24089. this.spritesEnabled = true;
  24090. /**
  24091. * All of the sprite managers added to this scene
  24092. * @see http://doc.babylonjs.com/babylon101/sprites
  24093. */
  24094. this.spriteManagers = new Array();
  24095. /**
  24096. * The list of layers (background and foreground) of the scene
  24097. */
  24098. this.layers = new Array();
  24099. /**
  24100. * The list of effect layers (highlights/glow) added to the scene
  24101. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24102. * @see http://doc.babylonjs.com/how_to/glow_layer
  24103. */
  24104. this.effectLayers = new Array();
  24105. // Skeletons
  24106. this._skeletonsEnabled = true;
  24107. /**
  24108. * The list of skeletons added to the scene
  24109. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24110. */
  24111. this.skeletons = new Array();
  24112. // Morph targets
  24113. /**
  24114. * The list of morph target managers added to the scene
  24115. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24116. */
  24117. this.morphTargetManagers = new Array();
  24118. // Lens flares
  24119. /**
  24120. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24121. */
  24122. this.lensFlaresEnabled = true;
  24123. /**
  24124. * The list of lens flare system added to the scene
  24125. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24126. */
  24127. this.lensFlareSystems = new Array();
  24128. // Collisions
  24129. /**
  24130. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24131. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24132. */
  24133. this.collisionsEnabled = true;
  24134. /**
  24135. * Defines the gravity applied to this scene (used only for collisions)
  24136. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24137. */
  24138. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24139. // Postprocesses
  24140. /**
  24141. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24142. */
  24143. this.postProcessesEnabled = true;
  24144. /**
  24145. * The list of postprocesses added to the scene
  24146. */
  24147. this.postProcesses = new Array();
  24148. // Customs render targets
  24149. /**
  24150. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24151. */
  24152. this.renderTargetsEnabled = true;
  24153. /**
  24154. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24155. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24156. */
  24157. this.dumpNextRenderTargets = false;
  24158. /**
  24159. * The list of user defined render targets added to the scene
  24160. */
  24161. this.customRenderTargets = new Array();
  24162. /**
  24163. * Gets the list of meshes imported to the scene through SceneLoader
  24164. */
  24165. this.importedMeshesFiles = new Array();
  24166. // Probes
  24167. /**
  24168. * Gets or sets a boolean indicating if probes are enabled on this scene
  24169. */
  24170. this.probesEnabled = true;
  24171. /**
  24172. * The list of reflection probes added to the scene
  24173. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24174. */
  24175. this.reflectionProbes = new Array();
  24176. /** @hidden */
  24177. this._actionManagers = new Array();
  24178. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24179. // Procedural textures
  24180. /**
  24181. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24182. */
  24183. this.proceduralTexturesEnabled = true;
  24184. /**
  24185. * The list of procedural textures added to the scene
  24186. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24187. */
  24188. this.proceduralTextures = new Array();
  24189. /**
  24190. * The list of sound tracks added to the scene
  24191. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24192. */
  24193. this.soundTracks = new Array();
  24194. this._audioEnabled = true;
  24195. this._headphone = false;
  24196. // Performance counters
  24197. this._totalVertices = new BABYLON.PerfCounter();
  24198. /** @hidden */
  24199. this._activeIndices = new BABYLON.PerfCounter();
  24200. /** @hidden */
  24201. this._activeParticles = new BABYLON.PerfCounter();
  24202. /** @hidden */
  24203. this._activeBones = new BABYLON.PerfCounter();
  24204. this._animationTime = 0;
  24205. /**
  24206. * Gets or sets a general scale for animation speed
  24207. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24208. */
  24209. this.animationTimeScale = 1;
  24210. this._renderId = 0;
  24211. this._executeWhenReadyTimeoutId = -1;
  24212. this._intermediateRendering = false;
  24213. this._viewUpdateFlag = -1;
  24214. this._projectionUpdateFlag = -1;
  24215. this._alternateViewUpdateFlag = -1;
  24216. this._alternateProjectionUpdateFlag = -1;
  24217. /** @hidden */
  24218. this._toBeDisposed = new BABYLON.SmartArray(256);
  24219. this._activeRequests = new Array();
  24220. this._pendingData = new Array();
  24221. this._isDisposed = false;
  24222. /**
  24223. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24224. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24225. */
  24226. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24227. this._activeMeshes = new BABYLON.SmartArray(256);
  24228. this._processedMaterials = new BABYLON.SmartArray(256);
  24229. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24230. /** @hidden */
  24231. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24232. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24233. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24234. /** @hidden */
  24235. this._activeAnimatables = new Array();
  24236. this._transformMatrix = BABYLON.Matrix.Zero();
  24237. this._useAlternateCameraConfiguration = false;
  24238. this._alternateRendering = false;
  24239. /**
  24240. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24241. * This is useful if there are more lights that the maximum simulteanous authorized
  24242. */
  24243. this.requireLightSorting = false;
  24244. this._depthRenderer = {};
  24245. this._activeMeshesFrozen = false;
  24246. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24247. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24248. this._engine.scenes.push(this);
  24249. this._uid = null;
  24250. this._renderingManager = new BABYLON.RenderingManager(this);
  24251. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24252. if (BABYLON.OutlineRenderer) {
  24253. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24254. }
  24255. if (BABYLON.Tools.IsWindowObjectExist()) {
  24256. this.attachControl();
  24257. }
  24258. //simplification queue
  24259. if (BABYLON.SimplificationQueue) {
  24260. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24261. }
  24262. //collision coordinator initialization. For now legacy per default.
  24263. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24264. // Uniform Buffer
  24265. this._createUbo();
  24266. // Default Image processing definition.
  24267. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24268. }
  24269. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24270. /** The fog is deactivated */
  24271. get: function () {
  24272. return Scene._FOGMODE_NONE;
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24278. /** The fog density is following an exponential function */
  24279. get: function () {
  24280. return Scene._FOGMODE_EXP;
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24286. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24287. get: function () {
  24288. return Scene._FOGMODE_EXP2;
  24289. },
  24290. enumerable: true,
  24291. configurable: true
  24292. });
  24293. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24294. /** The fog density is following a linear function. */
  24295. get: function () {
  24296. return Scene._FOGMODE_LINEAR;
  24297. },
  24298. enumerable: true,
  24299. configurable: true
  24300. });
  24301. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24302. /**
  24303. * Texture used in all pbr material as the reflection texture.
  24304. * As in the majority of the scene they are the same (exception for multi room and so on),
  24305. * this is easier to reference from here than from all the materials.
  24306. */
  24307. get: function () {
  24308. return this._environmentTexture;
  24309. },
  24310. /**
  24311. * Texture used in all pbr material as the reflection texture.
  24312. * As in the majority of the scene they are the same (exception for multi room and so on),
  24313. * this is easier to set here than in all the materials.
  24314. */
  24315. set: function (value) {
  24316. if (this._environmentTexture === value) {
  24317. return;
  24318. }
  24319. this._environmentTexture = value;
  24320. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24321. },
  24322. enumerable: true,
  24323. configurable: true
  24324. });
  24325. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24326. /**
  24327. * Default image processing configuration used either in the rendering
  24328. * Forward main pass or through the imageProcessingPostProcess if present.
  24329. * As in the majority of the scene they are the same (exception for multi camera),
  24330. * this is easier to reference from here than from all the materials and post process.
  24331. *
  24332. * No setter as we it is a shared configuration, you can set the values instead.
  24333. */
  24334. get: function () {
  24335. return this._imageProcessingConfiguration;
  24336. },
  24337. enumerable: true,
  24338. configurable: true
  24339. });
  24340. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24341. get: function () {
  24342. return this._forceWireframe;
  24343. },
  24344. /**
  24345. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24346. */
  24347. set: function (value) {
  24348. if (this._forceWireframe === value) {
  24349. return;
  24350. }
  24351. this._forceWireframe = value;
  24352. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24353. },
  24354. enumerable: true,
  24355. configurable: true
  24356. });
  24357. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24358. get: function () {
  24359. return this._forcePointsCloud;
  24360. },
  24361. /**
  24362. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24363. */
  24364. set: function (value) {
  24365. if (this._forcePointsCloud === value) {
  24366. return;
  24367. }
  24368. this._forcePointsCloud = value;
  24369. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24370. },
  24371. enumerable: true,
  24372. configurable: true
  24373. });
  24374. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24375. /**
  24376. * Gets or sets the animation properties override
  24377. */
  24378. get: function () {
  24379. return this._animationPropertiesOverride;
  24380. },
  24381. set: function (value) {
  24382. this._animationPropertiesOverride = value;
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. Object.defineProperty(Scene.prototype, "onDispose", {
  24388. /** Sets a function to be executed when this scene is disposed. */
  24389. set: function (callback) {
  24390. if (this._onDisposeObserver) {
  24391. this.onDisposeObservable.remove(this._onDisposeObserver);
  24392. }
  24393. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24394. },
  24395. enumerable: true,
  24396. configurable: true
  24397. });
  24398. Object.defineProperty(Scene.prototype, "beforeRender", {
  24399. /** Sets a function to be executed before rendering this scene */
  24400. set: function (callback) {
  24401. if (this._onBeforeRenderObserver) {
  24402. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24403. }
  24404. if (callback) {
  24405. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24406. }
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(Scene.prototype, "afterRender", {
  24412. /** Sets a function to be executed after rendering this scene */
  24413. set: function (callback) {
  24414. if (this._onAfterRenderObserver) {
  24415. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24416. }
  24417. if (callback) {
  24418. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24419. }
  24420. },
  24421. enumerable: true,
  24422. configurable: true
  24423. });
  24424. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24425. /** Sets a function to be executed before rendering a camera*/
  24426. set: function (callback) {
  24427. if (this._onBeforeCameraRenderObserver) {
  24428. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24429. }
  24430. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24436. /** Sets a function to be executed after rendering a camera*/
  24437. set: function (callback) {
  24438. if (this._onAfterCameraRenderObserver) {
  24439. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24440. }
  24441. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24447. /**
  24448. * Gets the gamepad manager associated with the scene
  24449. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24450. */
  24451. get: function () {
  24452. if (!this._gamepadManager) {
  24453. this._gamepadManager = new BABYLON.GamepadManager(this);
  24454. }
  24455. return this._gamepadManager;
  24456. },
  24457. enumerable: true,
  24458. configurable: true
  24459. });
  24460. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24461. /**
  24462. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24463. */
  24464. get: function () {
  24465. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24471. get: function () {
  24472. return this._useRightHandedSystem;
  24473. },
  24474. /**
  24475. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24476. */
  24477. set: function (value) {
  24478. if (this._useRightHandedSystem === value) {
  24479. return;
  24480. }
  24481. this._useRightHandedSystem = value;
  24482. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24483. },
  24484. enumerable: true,
  24485. configurable: true
  24486. });
  24487. /**
  24488. * Sets the step Id used by deterministic lock step
  24489. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24490. * @param newStepId defines the step Id
  24491. */
  24492. Scene.prototype.setStepId = function (newStepId) {
  24493. this._currentStepId = newStepId;
  24494. };
  24495. ;
  24496. /**
  24497. * Gets the step Id used by deterministic lock step
  24498. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24499. * @returns the step Id
  24500. */
  24501. Scene.prototype.getStepId = function () {
  24502. return this._currentStepId;
  24503. };
  24504. ;
  24505. /**
  24506. * Gets the internal step used by deterministic lock step
  24507. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24508. * @returns the internal step
  24509. */
  24510. Scene.prototype.getInternalStep = function () {
  24511. return this._currentInternalStep;
  24512. };
  24513. ;
  24514. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24515. get: function () {
  24516. return this._fogEnabled;
  24517. },
  24518. /**
  24519. * Gets or sets a boolean indicating if fog is enabled on this scene
  24520. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24521. */
  24522. set: function (value) {
  24523. if (this._fogEnabled === value) {
  24524. return;
  24525. }
  24526. this._fogEnabled = value;
  24527. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Scene.prototype, "fogMode", {
  24533. get: function () {
  24534. return this._fogMode;
  24535. },
  24536. /**
  24537. * Gets or sets the fog mode to use
  24538. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24539. */
  24540. set: function (value) {
  24541. if (this._fogMode === value) {
  24542. return;
  24543. }
  24544. this._fogMode = value;
  24545. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24546. },
  24547. enumerable: true,
  24548. configurable: true
  24549. });
  24550. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24551. get: function () {
  24552. return this._shadowsEnabled;
  24553. },
  24554. /**
  24555. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24556. */
  24557. set: function (value) {
  24558. if (this._shadowsEnabled === value) {
  24559. return;
  24560. }
  24561. this._shadowsEnabled = value;
  24562. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24568. get: function () {
  24569. return this._lightsEnabled;
  24570. },
  24571. /**
  24572. * Gets or sets a boolean indicating if lights are enabled on this scene
  24573. */
  24574. set: function (value) {
  24575. if (this._lightsEnabled === value) {
  24576. return;
  24577. }
  24578. this._lightsEnabled = value;
  24579. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24580. },
  24581. enumerable: true,
  24582. configurable: true
  24583. });
  24584. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24585. /** The default material used on meshes when no material is affected */
  24586. get: function () {
  24587. if (!this._defaultMaterial) {
  24588. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24589. }
  24590. return this._defaultMaterial;
  24591. },
  24592. /** The default material used on meshes when no material is affected */
  24593. set: function (value) {
  24594. this._defaultMaterial = value;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24600. get: function () {
  24601. return this._texturesEnabled;
  24602. },
  24603. /**
  24604. * Gets or sets a boolean indicating if textures are enabled on this scene
  24605. */
  24606. set: function (value) {
  24607. if (this._texturesEnabled === value) {
  24608. return;
  24609. }
  24610. this._texturesEnabled = value;
  24611. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24612. },
  24613. enumerable: true,
  24614. configurable: true
  24615. });
  24616. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24617. get: function () {
  24618. return this._skeletonsEnabled;
  24619. },
  24620. /**
  24621. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24622. */
  24623. set: function (value) {
  24624. if (this._skeletonsEnabled === value) {
  24625. return;
  24626. }
  24627. this._skeletonsEnabled = value;
  24628. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24634. /**
  24635. * Gets the postprocess render pipeline manager
  24636. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24637. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24638. */
  24639. get: function () {
  24640. if (!this._postProcessRenderPipelineManager) {
  24641. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24642. }
  24643. return this._postProcessRenderPipelineManager;
  24644. },
  24645. enumerable: true,
  24646. configurable: true
  24647. });
  24648. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24649. /**
  24650. * Gets the main soundtrack associated with the scene
  24651. */
  24652. get: function () {
  24653. if (!this._mainSoundTrack) {
  24654. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24655. }
  24656. return this._mainSoundTrack;
  24657. },
  24658. enumerable: true,
  24659. configurable: true
  24660. });
  24661. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24662. /** @hidden */
  24663. get: function () {
  24664. return this._alternateRendering;
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24670. /**
  24671. * Gets the list of frustum planes (built from the active camera)
  24672. */
  24673. get: function () {
  24674. return this._frustumPlanes;
  24675. },
  24676. enumerable: true,
  24677. configurable: true
  24678. });
  24679. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24680. /**
  24681. * Gets the current geometry buffer associated to the scene.
  24682. */
  24683. get: function () {
  24684. return this._geometryBufferRenderer;
  24685. },
  24686. /**
  24687. * Sets the current geometry buffer for the scene.
  24688. */
  24689. set: function (geometryBufferRenderer) {
  24690. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24691. this._geometryBufferRenderer = geometryBufferRenderer;
  24692. }
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. Object.defineProperty(Scene.prototype, "debugLayer", {
  24698. /**
  24699. * Gets the debug layer (aka Inspector) associated with the scene
  24700. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24701. */
  24702. get: function () {
  24703. if (!this._debugLayer) {
  24704. this._debugLayer = new BABYLON.DebugLayer(this);
  24705. }
  24706. return this._debugLayer;
  24707. },
  24708. enumerable: true,
  24709. configurable: true
  24710. });
  24711. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24712. /**
  24713. * Gets a boolean indicating if collisions are processed on a web worker
  24714. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24715. */
  24716. get: function () {
  24717. return this._workerCollisions;
  24718. },
  24719. set: function (enabled) {
  24720. if (!BABYLON.CollisionCoordinatorLegacy) {
  24721. return;
  24722. }
  24723. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24724. this._workerCollisions = enabled;
  24725. if (this.collisionCoordinator) {
  24726. this.collisionCoordinator.destroy();
  24727. }
  24728. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24729. this.collisionCoordinator.init(this);
  24730. },
  24731. enumerable: true,
  24732. configurable: true
  24733. });
  24734. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24735. /**
  24736. * Gets the octree used to boost mesh selection (picking)
  24737. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24738. */
  24739. get: function () {
  24740. return this._selectionOctree;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24746. /**
  24747. * Gets the mesh that is currently under the pointer
  24748. */
  24749. get: function () {
  24750. return this._pointerOverMesh;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "pointerX", {
  24756. /**
  24757. * Gets the current on-screen X position of the pointer
  24758. */
  24759. get: function () {
  24760. return this._pointerX;
  24761. },
  24762. enumerable: true,
  24763. configurable: true
  24764. });
  24765. Object.defineProperty(Scene.prototype, "pointerY", {
  24766. /**
  24767. * Gets the current on-screen Y position of the pointer
  24768. */
  24769. get: function () {
  24770. return this._pointerY;
  24771. },
  24772. enumerable: true,
  24773. configurable: true
  24774. });
  24775. /**
  24776. * Gets the cached material (ie. the latest rendered one)
  24777. * @returns the cached material
  24778. */
  24779. Scene.prototype.getCachedMaterial = function () {
  24780. return this._cachedMaterial;
  24781. };
  24782. /**
  24783. * Gets the cached effect (ie. the latest rendered one)
  24784. * @returns the cached effect
  24785. */
  24786. Scene.prototype.getCachedEffect = function () {
  24787. return this._cachedEffect;
  24788. };
  24789. /**
  24790. * Gets the cached visibility state (ie. the latest rendered one)
  24791. * @returns the cached visibility state
  24792. */
  24793. Scene.prototype.getCachedVisibility = function () {
  24794. return this._cachedVisibility;
  24795. };
  24796. /**
  24797. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24798. * @param material defines the current material
  24799. * @param effect defines the current effect
  24800. * @param visibility defines the current visibility state
  24801. * @returns true if one parameter is not cached
  24802. */
  24803. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24804. if (visibility === void 0) { visibility = 1; }
  24805. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24806. };
  24807. /**
  24808. * Gets the bounding box renderer associated with the scene
  24809. * @returns a BoundingBoxRenderer
  24810. */
  24811. Scene.prototype.getBoundingBoxRenderer = function () {
  24812. if (!this._boundingBoxRenderer) {
  24813. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24814. }
  24815. return this._boundingBoxRenderer;
  24816. };
  24817. /**
  24818. * Gets the outline renderer associated with the scene
  24819. * @returns a OutlineRenderer
  24820. */
  24821. Scene.prototype.getOutlineRenderer = function () {
  24822. return this._outlineRenderer;
  24823. };
  24824. /**
  24825. * Gets the engine associated with the scene
  24826. * @returns an Engine
  24827. */
  24828. Scene.prototype.getEngine = function () {
  24829. return this._engine;
  24830. };
  24831. /**
  24832. * Gets the total number of vertices rendered per frame
  24833. * @returns the total number of vertices rendered per frame
  24834. */
  24835. Scene.prototype.getTotalVertices = function () {
  24836. return this._totalVertices.current;
  24837. };
  24838. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24839. /**
  24840. * Gets the performance counter for total vertices
  24841. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24842. */
  24843. get: function () {
  24844. return this._totalVertices;
  24845. },
  24846. enumerable: true,
  24847. configurable: true
  24848. });
  24849. /**
  24850. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24851. * @returns the total number of active indices rendered per frame
  24852. */
  24853. Scene.prototype.getActiveIndices = function () {
  24854. return this._activeIndices.current;
  24855. };
  24856. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24857. /**
  24858. * Gets the performance counter for active indices
  24859. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24860. */
  24861. get: function () {
  24862. return this._activeIndices;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Gets the total number of active particles rendered per frame
  24869. * @returns the total number of active particles rendered per frame
  24870. */
  24871. Scene.prototype.getActiveParticles = function () {
  24872. return this._activeParticles.current;
  24873. };
  24874. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24875. /**
  24876. * Gets the performance counter for active particles
  24877. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24878. */
  24879. get: function () {
  24880. return this._activeParticles;
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. /**
  24886. * Gets the total number of active bones rendered per frame
  24887. * @returns the total number of active bones rendered per frame
  24888. */
  24889. Scene.prototype.getActiveBones = function () {
  24890. return this._activeBones.current;
  24891. };
  24892. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24893. /**
  24894. * Gets the performance counter for active bones
  24895. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24896. */
  24897. get: function () {
  24898. return this._activeBones;
  24899. },
  24900. enumerable: true,
  24901. configurable: true
  24902. });
  24903. /** @hidden */
  24904. Scene.prototype.getInterFramePerfCounter = function () {
  24905. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24906. return 0;
  24907. };
  24908. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24909. /** @hidden */
  24910. get: function () {
  24911. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24912. return null;
  24913. },
  24914. enumerable: true,
  24915. configurable: true
  24916. });
  24917. /** @hidden */
  24918. Scene.prototype.getLastFrameDuration = function () {
  24919. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24920. return 0;
  24921. };
  24922. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24923. /** @hidden */
  24924. get: function () {
  24925. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24926. return null;
  24927. },
  24928. enumerable: true,
  24929. configurable: true
  24930. });
  24931. /** @hidden */
  24932. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24933. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24934. return 0;
  24935. };
  24936. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24937. /** @hidden */
  24938. get: function () {
  24939. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24940. return null;
  24941. },
  24942. enumerable: true,
  24943. configurable: true
  24944. });
  24945. /**
  24946. * Gets the array of active meshes
  24947. * @returns an array of AbstractMesh
  24948. */
  24949. Scene.prototype.getActiveMeshes = function () {
  24950. return this._activeMeshes;
  24951. };
  24952. /** @hidden */
  24953. Scene.prototype.getRenderTargetsDuration = function () {
  24954. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24955. return 0;
  24956. };
  24957. /** @hidden */
  24958. Scene.prototype.getRenderDuration = function () {
  24959. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24960. return 0;
  24961. };
  24962. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24963. /** @hidden */
  24964. get: function () {
  24965. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24966. return null;
  24967. },
  24968. enumerable: true,
  24969. configurable: true
  24970. });
  24971. /** @hidden */
  24972. Scene.prototype.getParticlesDuration = function () {
  24973. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24974. return 0;
  24975. };
  24976. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24977. /** @hidden */
  24978. get: function () {
  24979. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24980. return null;
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. /** @hidden */
  24986. Scene.prototype.getSpritesDuration = function () {
  24987. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24988. return 0;
  24989. };
  24990. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24991. /** @hidden */
  24992. get: function () {
  24993. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24994. return null;
  24995. },
  24996. enumerable: true,
  24997. configurable: true
  24998. });
  24999. /**
  25000. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25001. * @returns a number
  25002. */
  25003. Scene.prototype.getAnimationRatio = function () {
  25004. return this._animationRatio;
  25005. };
  25006. /**
  25007. * Gets an unique Id for the current frame
  25008. * @returns a number
  25009. */
  25010. Scene.prototype.getRenderId = function () {
  25011. return this._renderId;
  25012. };
  25013. /** Call this function if you want to manually increment the render Id*/
  25014. Scene.prototype.incrementRenderId = function () {
  25015. this._renderId++;
  25016. };
  25017. Scene.prototype._updatePointerPosition = function (evt) {
  25018. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25019. if (!canvasRect) {
  25020. return;
  25021. }
  25022. this._pointerX = evt.clientX - canvasRect.left;
  25023. this._pointerY = evt.clientY - canvasRect.top;
  25024. this._unTranslatedPointerX = this._pointerX;
  25025. this._unTranslatedPointerY = this._pointerY;
  25026. };
  25027. Scene.prototype._createUbo = function () {
  25028. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25029. this._sceneUbo.addUniform("viewProjection", 16);
  25030. this._sceneUbo.addUniform("view", 16);
  25031. };
  25032. Scene.prototype._createAlternateUbo = function () {
  25033. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25034. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25035. this._alternateSceneUbo.addUniform("view", 16);
  25036. };
  25037. // Pointers handling
  25038. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25039. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25040. if (result) {
  25041. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25042. }
  25043. return result;
  25044. };
  25045. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25046. if (pointerInfo.pickInfo) {
  25047. if (!pointerInfo.pickInfo.ray) {
  25048. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25049. }
  25050. }
  25051. };
  25052. /**
  25053. * Use this method to simulate a pointer move on a mesh
  25054. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25055. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25056. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25057. * @returns the current scene
  25058. */
  25059. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25060. var evt = new PointerEvent("pointermove", pointerEventInit);
  25061. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25062. return this;
  25063. }
  25064. return this._processPointerMove(pickResult, evt);
  25065. };
  25066. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25067. var canvas = this._engine.getRenderingCanvas();
  25068. if (!canvas) {
  25069. return this;
  25070. }
  25071. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25072. this.setPointerOverSprite(null);
  25073. this.setPointerOverMesh(pickResult.pickedMesh);
  25074. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25075. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25076. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25077. }
  25078. else {
  25079. canvas.style.cursor = this.hoverCursor;
  25080. }
  25081. }
  25082. else {
  25083. canvas.style.cursor = this.defaultCursor;
  25084. }
  25085. }
  25086. else {
  25087. this.setPointerOverMesh(null);
  25088. // Sprites
  25089. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25090. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25091. this.setPointerOverSprite(pickResult.pickedSprite);
  25092. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25093. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25094. }
  25095. else {
  25096. canvas.style.cursor = this.hoverCursor;
  25097. }
  25098. }
  25099. else {
  25100. this.setPointerOverSprite(null);
  25101. // Restore pointer
  25102. canvas.style.cursor = this.defaultCursor;
  25103. }
  25104. }
  25105. if (pickResult) {
  25106. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25107. if (this.onPointerMove) {
  25108. this.onPointerMove(evt, pickResult, type);
  25109. }
  25110. if (this.onPointerObservable.hasObservers()) {
  25111. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25112. this._setRayOnPointerInfo(pi);
  25113. this.onPointerObservable.notifyObservers(pi, type);
  25114. }
  25115. }
  25116. return this;
  25117. };
  25118. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25119. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25120. if (pickResult) {
  25121. pi.ray = pickResult.ray;
  25122. }
  25123. this.onPrePointerObservable.notifyObservers(pi, type);
  25124. if (pi.skipOnPointerObservable) {
  25125. return true;
  25126. }
  25127. else {
  25128. return false;
  25129. }
  25130. };
  25131. /**
  25132. * Use this method to simulate a pointer down on a mesh
  25133. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25134. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25135. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25136. * @returns the current scene
  25137. */
  25138. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25139. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25140. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25141. return this;
  25142. }
  25143. return this._processPointerDown(pickResult, evt);
  25144. };
  25145. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25146. var _this = this;
  25147. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25148. this._pickedDownMesh = pickResult.pickedMesh;
  25149. var actionManager = pickResult.pickedMesh.actionManager;
  25150. if (actionManager) {
  25151. if (actionManager.hasPickTriggers) {
  25152. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25153. switch (evt.button) {
  25154. case 0:
  25155. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25156. break;
  25157. case 1:
  25158. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25159. break;
  25160. case 2:
  25161. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25162. break;
  25163. }
  25164. }
  25165. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25166. window.setTimeout(function () {
  25167. 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);
  25168. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25169. if (_this._totalPointersPressed !== 0 &&
  25170. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25171. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25172. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25173. _this._startingPointerTime = 0;
  25174. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25175. }
  25176. }
  25177. }, Scene.LongPressDelay);
  25178. }
  25179. }
  25180. }
  25181. if (pickResult) {
  25182. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25183. if (this.onPointerDown) {
  25184. this.onPointerDown(evt, pickResult, type);
  25185. }
  25186. if (this.onPointerObservable.hasObservers()) {
  25187. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25188. this._setRayOnPointerInfo(pi);
  25189. this.onPointerObservable.notifyObservers(pi, type);
  25190. }
  25191. }
  25192. return this;
  25193. };
  25194. /**
  25195. * Use this method to simulate a pointer up on a mesh
  25196. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25197. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25198. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25199. * @returns the current scene
  25200. */
  25201. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25202. var evt = new PointerEvent("pointerup", pointerEventInit);
  25203. var clickInfo = new ClickInfo();
  25204. clickInfo.singleClick = true;
  25205. clickInfo.ignore = true;
  25206. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25207. return this;
  25208. }
  25209. return this._processPointerUp(pickResult, evt, clickInfo);
  25210. };
  25211. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25212. if (pickResult && pickResult && pickResult.pickedMesh) {
  25213. this._pickedUpMesh = pickResult.pickedMesh;
  25214. if (this._pickedDownMesh === this._pickedUpMesh) {
  25215. if (this.onPointerPick) {
  25216. this.onPointerPick(evt, pickResult);
  25217. }
  25218. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25219. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25220. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25221. this._setRayOnPointerInfo(pi);
  25222. this.onPointerObservable.notifyObservers(pi, type_1);
  25223. }
  25224. }
  25225. if (pickResult.pickedMesh.actionManager) {
  25226. if (clickInfo.ignore) {
  25227. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25228. }
  25229. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25230. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25231. }
  25232. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25233. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25234. }
  25235. }
  25236. }
  25237. if (this._pickedDownMesh &&
  25238. this._pickedDownMesh.actionManager &&
  25239. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25240. this._pickedDownMesh !== this._pickedUpMesh) {
  25241. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25242. }
  25243. var type = BABYLON.PointerEventTypes.POINTERUP;
  25244. if (this.onPointerObservable.hasObservers()) {
  25245. if (!clickInfo.ignore) {
  25246. if (!clickInfo.hasSwiped) {
  25247. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25248. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25249. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25250. this._setRayOnPointerInfo(pi);
  25251. this.onPointerObservable.notifyObservers(pi, type_2);
  25252. }
  25253. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25254. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25255. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25256. this._setRayOnPointerInfo(pi);
  25257. this.onPointerObservable.notifyObservers(pi, type_3);
  25258. }
  25259. }
  25260. }
  25261. else {
  25262. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25263. this._setRayOnPointerInfo(pi);
  25264. this.onPointerObservable.notifyObservers(pi, type);
  25265. }
  25266. }
  25267. if (this.onPointerUp) {
  25268. this.onPointerUp(evt, pickResult, type);
  25269. }
  25270. return this;
  25271. };
  25272. /**
  25273. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25274. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25275. * @returns true if the pointer was captured
  25276. */
  25277. Scene.prototype.isPointerCaptured = function (pointerId) {
  25278. if (pointerId === void 0) { pointerId = 0; }
  25279. return this._pointerCaptures[pointerId];
  25280. };
  25281. /**
  25282. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25283. * @param attachUp defines if you want to attach events to pointerup
  25284. * @param attachDown defines if you want to attach events to pointerdown
  25285. * @param attachMove defines if you want to attach events to pointermove
  25286. */
  25287. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25288. var _this = this;
  25289. if (attachUp === void 0) { attachUp = true; }
  25290. if (attachDown === void 0) { attachDown = true; }
  25291. if (attachMove === void 0) { attachMove = true; }
  25292. this._initActionManager = function (act, clickInfo) {
  25293. if (!_this._meshPickProceed) {
  25294. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25295. _this._currentPickResult = pickResult;
  25296. if (pickResult) {
  25297. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25298. }
  25299. _this._meshPickProceed = true;
  25300. }
  25301. return act;
  25302. };
  25303. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25304. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25305. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25306. btn !== _this._previousButtonPressed) {
  25307. _this._doubleClickOccured = false;
  25308. clickInfo.singleClick = true;
  25309. clickInfo.ignore = false;
  25310. cb(clickInfo, _this._currentPickResult);
  25311. }
  25312. };
  25313. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25314. var clickInfo = new ClickInfo();
  25315. _this._currentPickResult = null;
  25316. var act = null;
  25317. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25318. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25319. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25320. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25321. act = _this._initActionManager(act, clickInfo);
  25322. if (act)
  25323. checkPicking = act.hasPickTriggers;
  25324. }
  25325. if (checkPicking) {
  25326. var btn = evt.button;
  25327. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25328. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25329. if (!clickInfo.hasSwiped) {
  25330. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25331. if (!checkSingleClickImmediately) {
  25332. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25333. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25334. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25335. act = _this._initActionManager(act, clickInfo);
  25336. if (act)
  25337. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25338. }
  25339. }
  25340. if (checkSingleClickImmediately) {
  25341. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25342. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25343. btn !== _this._previousButtonPressed) {
  25344. clickInfo.singleClick = true;
  25345. cb(clickInfo, _this._currentPickResult);
  25346. }
  25347. }
  25348. // at least one double click is required to be check and exclusive double click is enabled
  25349. else {
  25350. // wait that no double click has been raised during the double click delay
  25351. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25352. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25353. }
  25354. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25355. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25356. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25357. act = _this._initActionManager(act, clickInfo);
  25358. if (act)
  25359. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25360. }
  25361. if (checkDoubleClick) {
  25362. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25363. if (btn === _this._previousButtonPressed &&
  25364. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25365. !_this._doubleClickOccured) {
  25366. // pointer has not moved for 2 clicks, it's a double click
  25367. if (!clickInfo.hasSwiped &&
  25368. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25369. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25370. _this._previousStartingPointerTime = 0;
  25371. _this._doubleClickOccured = true;
  25372. clickInfo.doubleClick = true;
  25373. clickInfo.ignore = false;
  25374. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25375. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25376. }
  25377. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25378. cb(clickInfo, _this._currentPickResult);
  25379. }
  25380. // if the two successive clicks are too far, it's just two simple clicks
  25381. else {
  25382. _this._doubleClickOccured = false;
  25383. _this._previousStartingPointerTime = _this._startingPointerTime;
  25384. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25385. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25386. _this._previousButtonPressed = btn;
  25387. if (Scene.ExclusiveDoubleClickMode) {
  25388. if (_this._previousDelayedSimpleClickTimeout) {
  25389. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25390. }
  25391. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25392. cb(clickInfo, _this._previousPickResult);
  25393. }
  25394. else {
  25395. cb(clickInfo, _this._currentPickResult);
  25396. }
  25397. }
  25398. }
  25399. // just the first click of the double has been raised
  25400. else {
  25401. _this._doubleClickOccured = false;
  25402. _this._previousStartingPointerTime = _this._startingPointerTime;
  25403. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25404. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25405. _this._previousButtonPressed = btn;
  25406. }
  25407. }
  25408. }
  25409. }
  25410. clickInfo.ignore = true;
  25411. cb(clickInfo, _this._currentPickResult);
  25412. };
  25413. this._spritePredicate = function (sprite) {
  25414. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25415. };
  25416. this._onPointerMove = function (evt) {
  25417. _this._updatePointerPosition(evt);
  25418. // PreObservable support
  25419. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25420. return;
  25421. }
  25422. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25423. return;
  25424. }
  25425. if (!_this.pointerMovePredicate) {
  25426. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25427. }
  25428. // Meshes
  25429. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25430. _this._processPointerMove(pickResult, evt);
  25431. };
  25432. this._onPointerDown = function (evt) {
  25433. _this._totalPointersPressed++;
  25434. _this._pickedDownMesh = null;
  25435. _this._meshPickProceed = false;
  25436. _this._updatePointerPosition(evt);
  25437. if (_this.preventDefaultOnPointerDown && canvas) {
  25438. evt.preventDefault();
  25439. canvas.focus();
  25440. }
  25441. // PreObservable support
  25442. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25443. return;
  25444. }
  25445. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25446. return;
  25447. }
  25448. _this._pointerCaptures[evt.pointerId] = true;
  25449. _this._startingPointerPosition.x = _this._pointerX;
  25450. _this._startingPointerPosition.y = _this._pointerY;
  25451. _this._startingPointerTime = Date.now();
  25452. if (!_this.pointerDownPredicate) {
  25453. _this.pointerDownPredicate = function (mesh) {
  25454. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25455. };
  25456. }
  25457. // Meshes
  25458. _this._pickedDownMesh = null;
  25459. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25460. _this._processPointerDown(pickResult, evt);
  25461. // Sprites
  25462. _this._pickedDownSprite = null;
  25463. if (_this.spriteManagers.length > 0) {
  25464. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25465. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25466. if (pickResult.pickedSprite.actionManager) {
  25467. _this._pickedDownSprite = pickResult.pickedSprite;
  25468. switch (evt.button) {
  25469. case 0:
  25470. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25471. break;
  25472. case 1:
  25473. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25474. break;
  25475. case 2:
  25476. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25477. break;
  25478. }
  25479. if (pickResult.pickedSprite.actionManager) {
  25480. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25481. }
  25482. }
  25483. }
  25484. }
  25485. };
  25486. this._onPointerUp = function (evt) {
  25487. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25488. return; // So we need to test it the pointer down was pressed before.
  25489. }
  25490. _this._totalPointersPressed--;
  25491. _this._pickedUpMesh = null;
  25492. _this._meshPickProceed = false;
  25493. _this._updatePointerPosition(evt);
  25494. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25495. // PreObservable support
  25496. if (_this.onPrePointerObservable.hasObservers()) {
  25497. if (!clickInfo.ignore) {
  25498. if (!clickInfo.hasSwiped) {
  25499. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25500. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25501. return;
  25502. }
  25503. }
  25504. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25505. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25506. return;
  25507. }
  25508. }
  25509. }
  25510. }
  25511. else {
  25512. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25513. return;
  25514. }
  25515. }
  25516. }
  25517. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25518. return;
  25519. }
  25520. _this._pointerCaptures[evt.pointerId] = false;
  25521. if (!_this.pointerUpPredicate) {
  25522. _this.pointerUpPredicate = function (mesh) {
  25523. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25524. };
  25525. }
  25526. // Meshes
  25527. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25528. _this._initActionManager(null, clickInfo);
  25529. }
  25530. if (!pickResult) {
  25531. pickResult = _this._currentPickResult;
  25532. }
  25533. _this._processPointerUp(pickResult, evt, clickInfo);
  25534. // Sprites
  25535. if (!clickInfo.ignore) {
  25536. if (_this.spriteManagers.length > 0) {
  25537. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25538. if (spritePickResult) {
  25539. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25540. if (spritePickResult.pickedSprite.actionManager) {
  25541. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25542. if (spritePickResult.pickedSprite.actionManager) {
  25543. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25544. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25545. }
  25546. }
  25547. }
  25548. }
  25549. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25550. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25551. }
  25552. }
  25553. }
  25554. }
  25555. _this._previousPickResult = _this._currentPickResult;
  25556. });
  25557. };
  25558. this._onKeyDown = function (evt) {
  25559. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25560. if (_this.onPreKeyboardObservable.hasObservers()) {
  25561. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25562. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25563. if (pi.skipOnPointerObservable) {
  25564. return;
  25565. }
  25566. }
  25567. if (_this.onKeyboardObservable.hasObservers()) {
  25568. var pi = new BABYLON.KeyboardInfo(type, evt);
  25569. _this.onKeyboardObservable.notifyObservers(pi, type);
  25570. }
  25571. if (_this.actionManager) {
  25572. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25573. }
  25574. };
  25575. this._onKeyUp = function (evt) {
  25576. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25577. if (_this.onPreKeyboardObservable.hasObservers()) {
  25578. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25579. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25580. if (pi.skipOnPointerObservable) {
  25581. return;
  25582. }
  25583. }
  25584. if (_this.onKeyboardObservable.hasObservers()) {
  25585. var pi = new BABYLON.KeyboardInfo(type, evt);
  25586. _this.onKeyboardObservable.notifyObservers(pi, type);
  25587. }
  25588. if (_this.actionManager) {
  25589. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25590. }
  25591. };
  25592. var engine = this.getEngine();
  25593. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25594. if (!canvas) {
  25595. return;
  25596. }
  25597. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25598. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25599. });
  25600. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25601. if (!canvas) {
  25602. return;
  25603. }
  25604. canvas.removeEventListener("keydown", _this._onKeyDown);
  25605. canvas.removeEventListener("keyup", _this._onKeyUp);
  25606. });
  25607. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25608. var canvas = this._engine.getRenderingCanvas();
  25609. if (!canvas) {
  25610. return;
  25611. }
  25612. if (attachMove) {
  25613. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25614. // Wheel
  25615. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25616. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25617. }
  25618. if (attachDown) {
  25619. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25620. }
  25621. if (attachUp) {
  25622. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25623. }
  25624. canvas.tabIndex = 1;
  25625. };
  25626. /** Detaches all event handlers*/
  25627. Scene.prototype.detachControl = function () {
  25628. var engine = this.getEngine();
  25629. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25630. var canvas = engine.getRenderingCanvas();
  25631. if (!canvas) {
  25632. return;
  25633. }
  25634. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25635. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25636. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25637. if (this._onCanvasBlurObserver) {
  25638. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25639. }
  25640. if (this._onCanvasFocusObserver) {
  25641. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25642. }
  25643. // Wheel
  25644. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25645. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25646. // Keyboard
  25647. canvas.removeEventListener("keydown", this._onKeyDown);
  25648. canvas.removeEventListener("keyup", this._onKeyUp);
  25649. // Observables
  25650. this.onKeyboardObservable.clear();
  25651. this.onPreKeyboardObservable.clear();
  25652. this.onPointerObservable.clear();
  25653. this.onPrePointerObservable.clear();
  25654. };
  25655. /**
  25656. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25657. * Delay loaded resources are not taking in account
  25658. * @return true if all required resources are ready
  25659. */
  25660. Scene.prototype.isReady = function () {
  25661. if (this._isDisposed) {
  25662. return false;
  25663. }
  25664. if (this._pendingData.length > 0) {
  25665. return false;
  25666. }
  25667. var index;
  25668. var engine = this.getEngine();
  25669. // Geometries
  25670. for (index = 0; index < this._geometries.length; index++) {
  25671. var geometry = this._geometries[index];
  25672. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25673. return false;
  25674. }
  25675. }
  25676. // Meshes
  25677. for (index = 0; index < this.meshes.length; index++) {
  25678. var mesh = this.meshes[index];
  25679. if (!mesh.isEnabled()) {
  25680. continue;
  25681. }
  25682. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25683. continue;
  25684. }
  25685. if (!mesh.isReady(true)) {
  25686. return false;
  25687. }
  25688. // Effect layers
  25689. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25690. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25691. var layer = _a[_i];
  25692. if (!layer.hasMesh(mesh)) {
  25693. continue;
  25694. }
  25695. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25696. var subMesh = _c[_b];
  25697. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25698. return false;
  25699. }
  25700. }
  25701. }
  25702. }
  25703. // Post-processes
  25704. if (this.activeCameras && this.activeCameras.length > 0) {
  25705. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25706. var camera = _e[_d];
  25707. if (!camera.isReady(true)) {
  25708. return false;
  25709. }
  25710. }
  25711. }
  25712. else if (this.activeCamera) {
  25713. if (!this.activeCamera.isReady(true)) {
  25714. return false;
  25715. }
  25716. }
  25717. // Particles
  25718. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25719. var particleSystem = _g[_f];
  25720. if (!particleSystem.isReady()) {
  25721. return false;
  25722. }
  25723. }
  25724. return true;
  25725. };
  25726. /** Resets all cached information relative to material (including effect and visibility) */
  25727. Scene.prototype.resetCachedMaterial = function () {
  25728. this._cachedMaterial = null;
  25729. this._cachedEffect = null;
  25730. this._cachedVisibility = null;
  25731. };
  25732. /**
  25733. * Registers a function to be called before every frame render
  25734. * @param func defines the function to register
  25735. */
  25736. Scene.prototype.registerBeforeRender = function (func) {
  25737. this.onBeforeRenderObservable.add(func);
  25738. };
  25739. /**
  25740. * Unregisters a function called before every frame render
  25741. * @param func defines the function to unregister
  25742. */
  25743. Scene.prototype.unregisterBeforeRender = function (func) {
  25744. this.onBeforeRenderObservable.removeCallback(func);
  25745. };
  25746. /**
  25747. * Registers a function to be called after every frame render
  25748. * @param func defines the function to register
  25749. */
  25750. Scene.prototype.registerAfterRender = function (func) {
  25751. this.onAfterRenderObservable.add(func);
  25752. };
  25753. /**
  25754. * Unregisters a function called after every frame render
  25755. * @param func defines the function to unregister
  25756. */
  25757. Scene.prototype.unregisterAfterRender = function (func) {
  25758. this.onAfterRenderObservable.removeCallback(func);
  25759. };
  25760. Scene.prototype._executeOnceBeforeRender = function (func) {
  25761. var _this = this;
  25762. var execFunc = function () {
  25763. func();
  25764. setTimeout(function () {
  25765. _this.unregisterBeforeRender(execFunc);
  25766. });
  25767. };
  25768. this.registerBeforeRender(execFunc);
  25769. };
  25770. /**
  25771. * The provided function will run before render once and will be disposed afterwards.
  25772. * A timeout delay can be provided so that the function will be executed in N ms.
  25773. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25774. * @param func The function to be executed.
  25775. * @param timeout optional delay in ms
  25776. */
  25777. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25778. var _this = this;
  25779. if (timeout !== undefined) {
  25780. setTimeout(function () {
  25781. _this._executeOnceBeforeRender(func);
  25782. }, timeout);
  25783. }
  25784. else {
  25785. this._executeOnceBeforeRender(func);
  25786. }
  25787. };
  25788. /** @hidden */
  25789. Scene.prototype._addPendingData = function (data) {
  25790. this._pendingData.push(data);
  25791. };
  25792. /** @hidden */
  25793. Scene.prototype._removePendingData = function (data) {
  25794. var wasLoading = this.isLoading;
  25795. var index = this._pendingData.indexOf(data);
  25796. if (index !== -1) {
  25797. this._pendingData.splice(index, 1);
  25798. }
  25799. if (wasLoading && !this.isLoading) {
  25800. this.onDataLoadedObservable.notifyObservers(this);
  25801. }
  25802. };
  25803. /**
  25804. * Returns the number of items waiting to be loaded
  25805. * @returns the number of items waiting to be loaded
  25806. */
  25807. Scene.prototype.getWaitingItemsCount = function () {
  25808. return this._pendingData.length;
  25809. };
  25810. Object.defineProperty(Scene.prototype, "isLoading", {
  25811. /**
  25812. * Returns a boolean indicating if the scene is still loading data
  25813. */
  25814. get: function () {
  25815. return this._pendingData.length > 0;
  25816. },
  25817. enumerable: true,
  25818. configurable: true
  25819. });
  25820. /**
  25821. * Registers a function to be executed when the scene is ready
  25822. * @param {Function} func - the function to be executed
  25823. */
  25824. Scene.prototype.executeWhenReady = function (func) {
  25825. var _this = this;
  25826. this.onReadyObservable.add(func);
  25827. if (this._executeWhenReadyTimeoutId !== -1) {
  25828. return;
  25829. }
  25830. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25831. _this._checkIsReady();
  25832. }, 150);
  25833. };
  25834. /**
  25835. * Returns a promise that resolves when the scene is ready
  25836. * @returns A promise that resolves when the scene is ready
  25837. */
  25838. Scene.prototype.whenReadyAsync = function () {
  25839. var _this = this;
  25840. return new Promise(function (resolve) {
  25841. _this.executeWhenReady(function () {
  25842. resolve();
  25843. });
  25844. });
  25845. };
  25846. /** @hidden */
  25847. Scene.prototype._checkIsReady = function () {
  25848. var _this = this;
  25849. if (this.isReady()) {
  25850. this.onReadyObservable.notifyObservers(this);
  25851. this.onReadyObservable.clear();
  25852. this._executeWhenReadyTimeoutId = -1;
  25853. return;
  25854. }
  25855. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25856. _this._checkIsReady();
  25857. }, 150);
  25858. };
  25859. // Animations
  25860. /**
  25861. * Will start the animation sequence of a given target
  25862. * @param target defines the target
  25863. * @param from defines from which frame should animation start
  25864. * @param to defines until which frame should animation run.
  25865. * @param weight defines the weight to apply to the animation (1.0 by default)
  25866. * @param loop defines if the animation loops
  25867. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25868. * @param onAnimationEnd defines the function to be executed when the animation ends
  25869. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25870. * @returns the animatable object created for this animation
  25871. */
  25872. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25873. if (weight === void 0) { weight = 1.0; }
  25874. if (speedRatio === void 0) { speedRatio = 1.0; }
  25875. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25876. returnedAnimatable.weight = weight;
  25877. return returnedAnimatable;
  25878. };
  25879. /**
  25880. * Will start the animation sequence of a given target
  25881. * @param target defines the target
  25882. * @param from defines from which frame should animation start
  25883. * @param to defines until which frame should animation run.
  25884. * @param loop defines if the animation loops
  25885. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25886. * @param onAnimationEnd defines the function to be executed when the animation ends
  25887. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25888. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25889. * @returns the animatable object created for this animation
  25890. */
  25891. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25892. if (speedRatio === void 0) { speedRatio = 1.0; }
  25893. if (stopCurrent === void 0) { stopCurrent = true; }
  25894. if (from > to && speedRatio > 0) {
  25895. speedRatio *= -1;
  25896. }
  25897. if (stopCurrent) {
  25898. this.stopAnimation(target);
  25899. }
  25900. if (!animatable) {
  25901. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25902. }
  25903. // Local animations
  25904. if (target.animations) {
  25905. animatable.appendAnimations(target, target.animations);
  25906. }
  25907. // Children animations
  25908. if (target.getAnimatables) {
  25909. var animatables = target.getAnimatables();
  25910. for (var index = 0; index < animatables.length; index++) {
  25911. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25912. }
  25913. }
  25914. animatable.reset();
  25915. return animatable;
  25916. };
  25917. /**
  25918. * Begin a new animation on a given node
  25919. * @param target defines the target where the animation will take place
  25920. * @param animations defines the list of animations to start
  25921. * @param from defines the initial value
  25922. * @param to defines the final value
  25923. * @param loop defines if you want animation to loop (off by default)
  25924. * @param speedRatio defines the speed ratio to apply to all animations
  25925. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25926. * @returns the list of created animatables
  25927. */
  25928. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25929. if (speedRatio === undefined) {
  25930. speedRatio = 1.0;
  25931. }
  25932. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25933. return animatable;
  25934. };
  25935. /**
  25936. * Begin a new animation on a given node and its hierarchy
  25937. * @param target defines the root node where the animation will take place
  25938. * @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.
  25939. * @param animations defines the list of animations to start
  25940. * @param from defines the initial value
  25941. * @param to defines the final value
  25942. * @param loop defines if you want animation to loop (off by default)
  25943. * @param speedRatio defines the speed ratio to apply to all animations
  25944. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25945. * @returns the list of animatables created for all nodes
  25946. */
  25947. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25948. var children = target.getDescendants(directDescendantsOnly);
  25949. var result = [];
  25950. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25951. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25952. var child = children_1[_i];
  25953. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25954. }
  25955. return result;
  25956. };
  25957. /**
  25958. * Gets the animatable associated with a specific target
  25959. * @param target defines the target of the animatable
  25960. * @returns the required animatable if found
  25961. */
  25962. Scene.prototype.getAnimatableByTarget = function (target) {
  25963. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25964. if (this._activeAnimatables[index].target === target) {
  25965. return this._activeAnimatables[index];
  25966. }
  25967. }
  25968. return null;
  25969. };
  25970. /**
  25971. * Gets all animatables associated with a given target
  25972. * @param target defines the target to look animatables for
  25973. * @returns an array of Animatables
  25974. */
  25975. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25976. var result = [];
  25977. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25978. if (this._activeAnimatables[index].target === target) {
  25979. result.push(this._activeAnimatables[index]);
  25980. }
  25981. }
  25982. return result;
  25983. };
  25984. Object.defineProperty(Scene.prototype, "animatables", {
  25985. /**
  25986. * Gets all animatable attached to the scene
  25987. */
  25988. get: function () {
  25989. return this._activeAnimatables;
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. /**
  25995. * Will stop the animation of the given target
  25996. * @param target - the target
  25997. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25998. */
  25999. Scene.prototype.stopAnimation = function (target, animationName) {
  26000. var animatables = this.getAllAnimatablesByTarget(target);
  26001. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26002. var animatable = animatables_1[_i];
  26003. animatable.stop(animationName);
  26004. }
  26005. };
  26006. /**
  26007. * Stops and removes all animations that have been applied to the scene
  26008. */
  26009. Scene.prototype.stopAllAnimations = function () {
  26010. if (this._activeAnimatables) {
  26011. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26012. this._activeAnimatables[i].stop();
  26013. }
  26014. this._activeAnimatables = [];
  26015. }
  26016. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26017. var group = _a[_i];
  26018. group.stop();
  26019. }
  26020. };
  26021. Scene.prototype._animate = function () {
  26022. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26023. return;
  26024. }
  26025. // Getting time
  26026. var now = BABYLON.Tools.Now;
  26027. if (!this._animationTimeLast) {
  26028. if (this._pendingData.length > 0) {
  26029. return;
  26030. }
  26031. this._animationTimeLast = now;
  26032. }
  26033. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26034. this._animationTime += deltaTime;
  26035. this._animationTimeLast = now;
  26036. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26037. this._activeAnimatables[index]._animate(this._animationTime);
  26038. }
  26039. // Late animation bindings
  26040. this._processLateAnimationBindings();
  26041. };
  26042. /** @hidden */
  26043. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26044. var target = runtimeAnimation.target;
  26045. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26046. if (!target._lateAnimationHolders) {
  26047. target._lateAnimationHolders = {};
  26048. }
  26049. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26050. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26051. totalWeight: 0,
  26052. animations: [],
  26053. originalValue: originalValue
  26054. };
  26055. }
  26056. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26057. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26058. };
  26059. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26060. var normalizer = 1.0;
  26061. var finalPosition = BABYLON.Tmp.Vector3[0];
  26062. var finalScaling = BABYLON.Tmp.Vector3[1];
  26063. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26064. var startIndex = 0;
  26065. var originalAnimation = holder.animations[0];
  26066. var originalValue = holder.originalValue;
  26067. var scale = 1;
  26068. if (holder.totalWeight < 1.0) {
  26069. // We need to mix the original value in
  26070. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26071. scale = 1.0 - holder.totalWeight;
  26072. }
  26073. else {
  26074. startIndex = 1;
  26075. // We need to normalize the weights
  26076. normalizer = holder.totalWeight;
  26077. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26078. scale = originalAnimation.weight / normalizer;
  26079. if (scale == 1) {
  26080. return originalAnimation.currentValue;
  26081. }
  26082. }
  26083. finalScaling.scaleInPlace(scale);
  26084. finalPosition.scaleInPlace(scale);
  26085. finalQuaternion.scaleInPlace(scale);
  26086. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26087. var runtimeAnimation = holder.animations[animIndex];
  26088. var scale = runtimeAnimation.weight / normalizer;
  26089. var currentPosition = BABYLON.Tmp.Vector3[2];
  26090. var currentScaling = BABYLON.Tmp.Vector3[3];
  26091. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26092. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26093. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26094. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26095. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26096. }
  26097. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26098. return originalAnimation._workValue;
  26099. };
  26100. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26101. var originalAnimation = holder.animations[0];
  26102. var originalValue = holder.originalValue;
  26103. if (holder.animations.length === 1) {
  26104. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26105. }
  26106. var normalizer = 1.0;
  26107. var quaternions;
  26108. var weights;
  26109. if (holder.totalWeight < 1.0) {
  26110. var scale = 1.0 - holder.totalWeight;
  26111. quaternions = [];
  26112. weights = [];
  26113. quaternions.push(originalValue);
  26114. weights.push(scale);
  26115. }
  26116. else {
  26117. if (holder.animations.length === 2) { // Slerp as soon as we can
  26118. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26119. }
  26120. quaternions = [];
  26121. weights = [];
  26122. normalizer = holder.totalWeight;
  26123. }
  26124. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26125. var runtimeAnimation = holder.animations[animIndex];
  26126. quaternions.push(runtimeAnimation.currentValue);
  26127. weights.push(runtimeAnimation.weight / normalizer);
  26128. }
  26129. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26130. var cumulativeAmount = 0;
  26131. var cumulativeQuaternion = null;
  26132. for (var index = 0; index < quaternions.length;) {
  26133. if (!cumulativeQuaternion) {
  26134. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26135. cumulativeAmount = weights[index] + weights[index + 1];
  26136. index += 2;
  26137. continue;
  26138. }
  26139. cumulativeAmount += weights[index];
  26140. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26141. index++;
  26142. }
  26143. return cumulativeQuaternion;
  26144. };
  26145. Scene.prototype._processLateAnimationBindings = function () {
  26146. if (!this._registeredForLateAnimationBindings.length) {
  26147. return;
  26148. }
  26149. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26150. var target = this._registeredForLateAnimationBindings.data[index];
  26151. for (var path in target._lateAnimationHolders) {
  26152. var holder = target._lateAnimationHolders[path];
  26153. var originalAnimation = holder.animations[0];
  26154. var originalValue = holder.originalValue;
  26155. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26156. var finalValue = void 0;
  26157. if (matrixDecomposeMode) {
  26158. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26159. }
  26160. else {
  26161. var quaternionMode = originalValue.w !== undefined;
  26162. if (quaternionMode) {
  26163. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26164. }
  26165. else {
  26166. var startIndex = 0;
  26167. var normalizer = 1.0;
  26168. if (holder.totalWeight < 1.0) {
  26169. // We need to mix the original value in
  26170. if (originalValue.scale) {
  26171. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26172. }
  26173. else {
  26174. finalValue = originalValue * (1.0 - holder.totalWeight);
  26175. }
  26176. }
  26177. else {
  26178. // We need to normalize the weights
  26179. normalizer = holder.totalWeight;
  26180. var scale_1 = originalAnimation.weight / normalizer;
  26181. if (scale_1 !== 1) {
  26182. if (originalAnimation.currentValue.scale) {
  26183. finalValue = originalAnimation.currentValue.scale(scale_1);
  26184. }
  26185. else {
  26186. finalValue = originalAnimation.currentValue * scale_1;
  26187. }
  26188. }
  26189. else {
  26190. finalValue = originalAnimation.currentValue;
  26191. }
  26192. startIndex = 1;
  26193. }
  26194. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26195. var runtimeAnimation = holder.animations[animIndex];
  26196. var scale = runtimeAnimation.weight / normalizer;
  26197. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26198. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26199. }
  26200. else {
  26201. finalValue += runtimeAnimation.currentValue * scale;
  26202. }
  26203. }
  26204. }
  26205. }
  26206. target[path] = finalValue;
  26207. }
  26208. target._lateAnimationHolders = {};
  26209. }
  26210. this._registeredForLateAnimationBindings.reset();
  26211. };
  26212. // Matrix
  26213. /** @hidden */
  26214. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26215. this._useAlternateCameraConfiguration = active;
  26216. };
  26217. /**
  26218. * Gets the current view matrix
  26219. * @returns a Matrix
  26220. */
  26221. Scene.prototype.getViewMatrix = function () {
  26222. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26223. };
  26224. /**
  26225. * Gets the current projection matrix
  26226. * @returns a Matrix
  26227. */
  26228. Scene.prototype.getProjectionMatrix = function () {
  26229. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26230. };
  26231. /**
  26232. * Gets the current transform matrix
  26233. * @returns a Matrix made of View * Projection
  26234. */
  26235. Scene.prototype.getTransformMatrix = function () {
  26236. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26237. };
  26238. /**
  26239. * Sets the current transform matrix
  26240. * @param view defines the View matrix to use
  26241. * @param projection defines the Projection matrix to use
  26242. */
  26243. Scene.prototype.setTransformMatrix = function (view, projection) {
  26244. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26245. return;
  26246. }
  26247. this._viewUpdateFlag = view.updateFlag;
  26248. this._projectionUpdateFlag = projection.updateFlag;
  26249. this._viewMatrix = view;
  26250. this._projectionMatrix = projection;
  26251. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26252. // Update frustum
  26253. if (!this._frustumPlanes) {
  26254. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26255. }
  26256. else {
  26257. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26258. }
  26259. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26260. var otherCamera = this.activeCamera._alternateCamera;
  26261. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26262. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26263. }
  26264. if (this._sceneUbo.useUbo) {
  26265. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26266. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26267. this._sceneUbo.update();
  26268. }
  26269. };
  26270. /** @hidden */
  26271. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26272. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26273. return;
  26274. }
  26275. this._alternateViewUpdateFlag = view.updateFlag;
  26276. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26277. this._alternateViewMatrix = view;
  26278. this._alternateProjectionMatrix = projection;
  26279. if (!this._alternateTransformMatrix) {
  26280. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26281. }
  26282. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26283. if (!this._alternateSceneUbo) {
  26284. this._createAlternateUbo();
  26285. }
  26286. if (this._alternateSceneUbo.useUbo) {
  26287. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26288. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26289. this._alternateSceneUbo.update();
  26290. }
  26291. };
  26292. /**
  26293. * Gets the uniform buffer used to store scene data
  26294. * @returns a UniformBuffer
  26295. */
  26296. Scene.prototype.getSceneUniformBuffer = function () {
  26297. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26298. };
  26299. /**
  26300. * Gets an unique (relatively to the current scene) Id
  26301. * @returns an unique number for the scene
  26302. */
  26303. Scene.prototype.getUniqueId = function () {
  26304. var result = Scene._uniqueIdCounter;
  26305. Scene._uniqueIdCounter++;
  26306. return result;
  26307. };
  26308. /**
  26309. * Add a mesh to the list of scene's meshes
  26310. * @param newMesh defines the mesh to add
  26311. * @param recursive if all child meshes should also be added to the scene
  26312. */
  26313. Scene.prototype.addMesh = function (newMesh, recursive) {
  26314. var _this = this;
  26315. if (recursive === void 0) { recursive = false; }
  26316. this.meshes.push(newMesh);
  26317. //notify the collision coordinator
  26318. if (this.collisionCoordinator) {
  26319. this.collisionCoordinator.onMeshAdded(newMesh);
  26320. }
  26321. newMesh._resyncLightSources();
  26322. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26323. if (recursive) {
  26324. newMesh.getChildMeshes().forEach(function (m) {
  26325. _this.addMesh(m);
  26326. });
  26327. }
  26328. };
  26329. /**
  26330. * Remove a mesh for the list of scene's meshes
  26331. * @param toRemove defines the mesh to remove
  26332. * @param recursive if all child meshes should also be removed from the scene
  26333. * @returns the index where the mesh was in the mesh list
  26334. */
  26335. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26336. var _this = this;
  26337. if (recursive === void 0) { recursive = false; }
  26338. var index = this.meshes.indexOf(toRemove);
  26339. if (index !== -1) {
  26340. // Remove from the scene if mesh found
  26341. this.meshes.splice(index, 1);
  26342. }
  26343. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26344. if (recursive) {
  26345. toRemove.getChildMeshes().forEach(function (m) {
  26346. _this.removeMesh(m);
  26347. });
  26348. }
  26349. return index;
  26350. };
  26351. /**
  26352. * Add a transform node to the list of scene's transform nodes
  26353. * @param newTransformNode defines the transform node to add
  26354. */
  26355. Scene.prototype.addTransformNode = function (newTransformNode) {
  26356. this.transformNodes.push(newTransformNode);
  26357. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26358. };
  26359. /**
  26360. * Remove a transform node for the list of scene's transform nodes
  26361. * @param toRemove defines the transform node to remove
  26362. * @returns the index where the transform node was in the transform node list
  26363. */
  26364. Scene.prototype.removeTransformNode = function (toRemove) {
  26365. var index = this.transformNodes.indexOf(toRemove);
  26366. if (index !== -1) {
  26367. // Remove from the scene if found
  26368. this.transformNodes.splice(index, 1);
  26369. }
  26370. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26371. return index;
  26372. };
  26373. /**
  26374. * Remove a skeleton for the list of scene's skeletons
  26375. * @param toRemove defines the skeleton to remove
  26376. * @returns the index where the skeleton was in the skeleton list
  26377. */
  26378. Scene.prototype.removeSkeleton = function (toRemove) {
  26379. var index = this.skeletons.indexOf(toRemove);
  26380. if (index !== -1) {
  26381. // Remove from the scene if found
  26382. this.skeletons.splice(index, 1);
  26383. }
  26384. return index;
  26385. };
  26386. /**
  26387. * Remove a morph target for the list of scene's morph targets
  26388. * @param toRemove defines the morph target to remove
  26389. * @returns the index where the morph target was in the morph target list
  26390. */
  26391. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26392. var index = this.morphTargetManagers.indexOf(toRemove);
  26393. if (index !== -1) {
  26394. // Remove from the scene if found
  26395. this.morphTargetManagers.splice(index, 1);
  26396. }
  26397. return index;
  26398. };
  26399. /**
  26400. * Remove a light for the list of scene's lights
  26401. * @param toRemove defines the light to remove
  26402. * @returns the index where the light was in the light list
  26403. */
  26404. Scene.prototype.removeLight = function (toRemove) {
  26405. var index = this.lights.indexOf(toRemove);
  26406. if (index !== -1) {
  26407. // Remove from meshes
  26408. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26409. var mesh = _a[_i];
  26410. mesh._removeLightSource(toRemove);
  26411. }
  26412. // Remove from the scene if mesh found
  26413. this.lights.splice(index, 1);
  26414. this.sortLightsByPriority();
  26415. }
  26416. this.onLightRemovedObservable.notifyObservers(toRemove);
  26417. return index;
  26418. };
  26419. /**
  26420. * Remove a camera for the list of scene's cameras
  26421. * @param toRemove defines the camera to remove
  26422. * @returns the index where the camera was in the camera list
  26423. */
  26424. Scene.prototype.removeCamera = function (toRemove) {
  26425. var index = this.cameras.indexOf(toRemove);
  26426. if (index !== -1) {
  26427. // Remove from the scene if mesh found
  26428. this.cameras.splice(index, 1);
  26429. }
  26430. // Remove from activeCameras
  26431. var index2 = this.activeCameras.indexOf(toRemove);
  26432. if (index2 !== -1) {
  26433. // Remove from the scene if mesh found
  26434. this.activeCameras.splice(index2, 1);
  26435. }
  26436. // Reset the activeCamera
  26437. if (this.activeCamera === toRemove) {
  26438. if (this.cameras.length > 0) {
  26439. this.activeCamera = this.cameras[0];
  26440. }
  26441. else {
  26442. this.activeCamera = null;
  26443. }
  26444. }
  26445. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26446. return index;
  26447. };
  26448. /**
  26449. * Remove a particle system for the list of scene's particle systems
  26450. * @param toRemove defines the particle system to remove
  26451. * @returns the index where the particle system was in the particle system list
  26452. */
  26453. Scene.prototype.removeParticleSystem = function (toRemove) {
  26454. var index = this.particleSystems.indexOf(toRemove);
  26455. if (index !== -1) {
  26456. this.particleSystems.splice(index, 1);
  26457. }
  26458. return index;
  26459. };
  26460. /**
  26461. * Remove a animation for the list of scene's animations
  26462. * @param toRemove defines the animation to remove
  26463. * @returns the index where the animation was in the animation list
  26464. */
  26465. Scene.prototype.removeAnimation = function (toRemove) {
  26466. var index = this.animations.indexOf(toRemove);
  26467. if (index !== -1) {
  26468. this.animations.splice(index, 1);
  26469. }
  26470. return index;
  26471. };
  26472. /**
  26473. * Removes the given animation group from this scene.
  26474. * @param toRemove The animation group to remove
  26475. * @returns The index of the removed animation group
  26476. */
  26477. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26478. var index = this.animationGroups.indexOf(toRemove);
  26479. if (index !== -1) {
  26480. this.animationGroups.splice(index, 1);
  26481. }
  26482. return index;
  26483. };
  26484. /**
  26485. * Removes the given multi-material from this scene.
  26486. * @param toRemove The multi-material to remove
  26487. * @returns The index of the removed multi-material
  26488. */
  26489. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26490. var index = this.multiMaterials.indexOf(toRemove);
  26491. if (index !== -1) {
  26492. this.multiMaterials.splice(index, 1);
  26493. }
  26494. return index;
  26495. };
  26496. /**
  26497. * Removes the given material from this scene.
  26498. * @param toRemove The material to remove
  26499. * @returns The index of the removed material
  26500. */
  26501. Scene.prototype.removeMaterial = function (toRemove) {
  26502. var index = this.materials.indexOf(toRemove);
  26503. if (index !== -1) {
  26504. this.materials.splice(index, 1);
  26505. }
  26506. return index;
  26507. };
  26508. /**
  26509. * Removes the given lens flare system from this scene.
  26510. * @param toRemove The lens flare system to remove
  26511. * @returns The index of the removed lens flare system
  26512. */
  26513. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26514. var index = this.lensFlareSystems.indexOf(toRemove);
  26515. if (index !== -1) {
  26516. this.lensFlareSystems.splice(index, 1);
  26517. }
  26518. return index;
  26519. };
  26520. /**
  26521. * Removes the given action manager from this scene.
  26522. * @param toRemove The action manager to remove
  26523. * @returns The index of the removed action manager
  26524. */
  26525. Scene.prototype.removeActionManager = function (toRemove) {
  26526. var index = this._actionManagers.indexOf(toRemove);
  26527. if (index !== -1) {
  26528. this._actionManagers.splice(index, 1);
  26529. }
  26530. return index;
  26531. };
  26532. /**
  26533. * Removes the given effect layer from this scene.
  26534. * @param toRemove defines the effect layer to remove
  26535. * @returns the index of the removed effect layer
  26536. */
  26537. Scene.prototype.removeEffectLayer = function (toRemove) {
  26538. var index = this.effectLayers.indexOf(toRemove);
  26539. if (index !== -1) {
  26540. this.effectLayers.splice(index, 1);
  26541. }
  26542. return index;
  26543. };
  26544. /**
  26545. * Removes the given texture from this scene.
  26546. * @param toRemove The texture to remove
  26547. * @returns The index of the removed texture
  26548. */
  26549. Scene.prototype.removeTexture = function (toRemove) {
  26550. var index = this.textures.indexOf(toRemove);
  26551. if (index !== -1) {
  26552. this.textures.splice(index, 1);
  26553. }
  26554. return index;
  26555. };
  26556. /**
  26557. * Adds the given light to this scene
  26558. * @param newLight The light to add
  26559. */
  26560. Scene.prototype.addLight = function (newLight) {
  26561. this.lights.push(newLight);
  26562. this.sortLightsByPriority();
  26563. // Add light to all meshes (To support if the light is removed and then readded)
  26564. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26565. var mesh = _a[_i];
  26566. if (mesh._lightSources.indexOf(newLight) === -1) {
  26567. mesh._lightSources.push(newLight);
  26568. mesh._resyncLightSources();
  26569. }
  26570. }
  26571. this.onNewLightAddedObservable.notifyObservers(newLight);
  26572. };
  26573. /**
  26574. * Sorts the list list based on light priorities
  26575. */
  26576. Scene.prototype.sortLightsByPriority = function () {
  26577. if (this.requireLightSorting) {
  26578. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26579. }
  26580. };
  26581. /**
  26582. * Adds the given camera to this scene
  26583. * @param newCamera The camera to add
  26584. */
  26585. Scene.prototype.addCamera = function (newCamera) {
  26586. this.cameras.push(newCamera);
  26587. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26588. };
  26589. /**
  26590. * Adds the given skeleton to this scene
  26591. * @param newSkeleton The skeleton to add
  26592. */
  26593. Scene.prototype.addSkeleton = function (newSkeleton) {
  26594. this.skeletons.push(newSkeleton);
  26595. };
  26596. /**
  26597. * Adds the given particle system to this scene
  26598. * @param newParticleSystem The particle system to add
  26599. */
  26600. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26601. this.particleSystems.push(newParticleSystem);
  26602. };
  26603. /**
  26604. * Adds the given animation to this scene
  26605. * @param newAnimation The animation to add
  26606. */
  26607. Scene.prototype.addAnimation = function (newAnimation) {
  26608. this.animations.push(newAnimation);
  26609. };
  26610. /**
  26611. * Adds the given animation group to this scene.
  26612. * @param newAnimationGroup The animation group to add
  26613. */
  26614. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26615. this.animationGroups.push(newAnimationGroup);
  26616. };
  26617. /**
  26618. * Adds the given multi-material to this scene
  26619. * @param newMultiMaterial The multi-material to add
  26620. */
  26621. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26622. this.multiMaterials.push(newMultiMaterial);
  26623. };
  26624. /**
  26625. * Adds the given material to this scene
  26626. * @param newMaterial The material to add
  26627. */
  26628. Scene.prototype.addMaterial = function (newMaterial) {
  26629. this.materials.push(newMaterial);
  26630. };
  26631. /**
  26632. * Adds the given morph target to this scene
  26633. * @param newMorphTargetManager The morph target to add
  26634. */
  26635. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26636. this.morphTargetManagers.push(newMorphTargetManager);
  26637. };
  26638. /**
  26639. * Adds the given geometry to this scene
  26640. * @param newGeometry The geometry to add
  26641. */
  26642. Scene.prototype.addGeometry = function (newGeometry) {
  26643. this._geometries.push(newGeometry);
  26644. };
  26645. /**
  26646. * Adds the given lens flare system to this scene
  26647. * @param newLensFlareSystem The lens flare system to add
  26648. */
  26649. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26650. this.lensFlareSystems.push(newLensFlareSystem);
  26651. };
  26652. /**
  26653. * Adds the given effect layer to this scene
  26654. * @param newEffectLayer defines the effect layer to add
  26655. */
  26656. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26657. this.effectLayers.push(newEffectLayer);
  26658. };
  26659. /**
  26660. * Adds the given action manager to this scene
  26661. * @param newActionManager The action manager to add
  26662. */
  26663. Scene.prototype.addActionManager = function (newActionManager) {
  26664. this._actionManagers.push(newActionManager);
  26665. };
  26666. /**
  26667. * Adds the given texture to this scene.
  26668. * @param newTexture The texture to add
  26669. */
  26670. Scene.prototype.addTexture = function (newTexture) {
  26671. this.textures.push(newTexture);
  26672. };
  26673. /**
  26674. * Switch active camera
  26675. * @param newCamera defines the new active camera
  26676. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26677. */
  26678. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26679. if (attachControl === void 0) { attachControl = true; }
  26680. var canvas = this._engine.getRenderingCanvas();
  26681. if (!canvas) {
  26682. return;
  26683. }
  26684. if (this.activeCamera) {
  26685. this.activeCamera.detachControl(canvas);
  26686. }
  26687. this.activeCamera = newCamera;
  26688. if (attachControl) {
  26689. newCamera.attachControl(canvas);
  26690. }
  26691. };
  26692. /**
  26693. * sets the active camera of the scene using its ID
  26694. * @param id defines the camera's ID
  26695. * @return the new active camera or null if none found.
  26696. */
  26697. Scene.prototype.setActiveCameraByID = function (id) {
  26698. var camera = this.getCameraByID(id);
  26699. if (camera) {
  26700. this.activeCamera = camera;
  26701. return camera;
  26702. }
  26703. return null;
  26704. };
  26705. /**
  26706. * sets the active camera of the scene using its name
  26707. * @param name defines the camera's name
  26708. * @returns the new active camera or null if none found.
  26709. */
  26710. Scene.prototype.setActiveCameraByName = function (name) {
  26711. var camera = this.getCameraByName(name);
  26712. if (camera) {
  26713. this.activeCamera = camera;
  26714. return camera;
  26715. }
  26716. return null;
  26717. };
  26718. /**
  26719. * get an animation group using its name
  26720. * @param name defines the material's name
  26721. * @return the animation group or null if none found.
  26722. */
  26723. Scene.prototype.getAnimationGroupByName = function (name) {
  26724. for (var index = 0; index < this.animationGroups.length; index++) {
  26725. if (this.animationGroups[index].name === name) {
  26726. return this.animationGroups[index];
  26727. }
  26728. }
  26729. return null;
  26730. };
  26731. /**
  26732. * get a material using its id
  26733. * @param id defines the material's ID
  26734. * @return the material or null if none found.
  26735. */
  26736. Scene.prototype.getMaterialByID = function (id) {
  26737. for (var index = 0; index < this.materials.length; index++) {
  26738. if (this.materials[index].id === id) {
  26739. return this.materials[index];
  26740. }
  26741. }
  26742. return null;
  26743. };
  26744. /**
  26745. * Gets a material using its name
  26746. * @param name defines the material's name
  26747. * @return the material or null if none found.
  26748. */
  26749. Scene.prototype.getMaterialByName = function (name) {
  26750. for (var index = 0; index < this.materials.length; index++) {
  26751. if (this.materials[index].name === name) {
  26752. return this.materials[index];
  26753. }
  26754. }
  26755. return null;
  26756. };
  26757. /**
  26758. * Gets a lens flare system using its name
  26759. * @param name defines the name to look for
  26760. * @returns the lens flare system or null if not found
  26761. */
  26762. Scene.prototype.getLensFlareSystemByName = function (name) {
  26763. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26764. if (this.lensFlareSystems[index].name === name) {
  26765. return this.lensFlareSystems[index];
  26766. }
  26767. }
  26768. return null;
  26769. };
  26770. /**
  26771. * Gets a lens flare system using its id
  26772. * @param id defines the id to look for
  26773. * @returns the lens flare system or null if not found
  26774. */
  26775. Scene.prototype.getLensFlareSystemByID = function (id) {
  26776. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26777. if (this.lensFlareSystems[index].id === id) {
  26778. return this.lensFlareSystems[index];
  26779. }
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * Gets a camera using its id
  26785. * @param id defines the id to look for
  26786. * @returns the camera or null if not found
  26787. */
  26788. Scene.prototype.getCameraByID = function (id) {
  26789. for (var index = 0; index < this.cameras.length; index++) {
  26790. if (this.cameras[index].id === id) {
  26791. return this.cameras[index];
  26792. }
  26793. }
  26794. return null;
  26795. };
  26796. /**
  26797. * Gets a camera using its unique id
  26798. * @param uniqueId defines the unique id to look for
  26799. * @returns the camera or null if not found
  26800. */
  26801. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26802. for (var index = 0; index < this.cameras.length; index++) {
  26803. if (this.cameras[index].uniqueId === uniqueId) {
  26804. return this.cameras[index];
  26805. }
  26806. }
  26807. return null;
  26808. };
  26809. /**
  26810. * Gets a camera using its name
  26811. * @param name defines the camera's name
  26812. * @return the camera or null if none found.
  26813. */
  26814. Scene.prototype.getCameraByName = function (name) {
  26815. for (var index = 0; index < this.cameras.length; index++) {
  26816. if (this.cameras[index].name === name) {
  26817. return this.cameras[index];
  26818. }
  26819. }
  26820. return null;
  26821. };
  26822. /**
  26823. * Gets a bone using its id
  26824. * @param id defines the bone's id
  26825. * @return the bone or null if not found
  26826. */
  26827. Scene.prototype.getBoneByID = function (id) {
  26828. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26829. var skeleton = this.skeletons[skeletonIndex];
  26830. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26831. if (skeleton.bones[boneIndex].id === id) {
  26832. return skeleton.bones[boneIndex];
  26833. }
  26834. }
  26835. }
  26836. return null;
  26837. };
  26838. /**
  26839. * Gets a bone using its id
  26840. * @param name defines the bone's name
  26841. * @return the bone or null if not found
  26842. */
  26843. Scene.prototype.getBoneByName = function (name) {
  26844. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26845. var skeleton = this.skeletons[skeletonIndex];
  26846. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26847. if (skeleton.bones[boneIndex].name === name) {
  26848. return skeleton.bones[boneIndex];
  26849. }
  26850. }
  26851. }
  26852. return null;
  26853. };
  26854. /**
  26855. * Gets a light node using its name
  26856. * @param name defines the the light's name
  26857. * @return the light or null if none found.
  26858. */
  26859. Scene.prototype.getLightByName = function (name) {
  26860. for (var index = 0; index < this.lights.length; index++) {
  26861. if (this.lights[index].name === name) {
  26862. return this.lights[index];
  26863. }
  26864. }
  26865. return null;
  26866. };
  26867. /**
  26868. * Gets a light node using its id
  26869. * @param id defines the light's id
  26870. * @return the light or null if none found.
  26871. */
  26872. Scene.prototype.getLightByID = function (id) {
  26873. for (var index = 0; index < this.lights.length; index++) {
  26874. if (this.lights[index].id === id) {
  26875. return this.lights[index];
  26876. }
  26877. }
  26878. return null;
  26879. };
  26880. /**
  26881. * Gets a light node using its scene-generated unique ID
  26882. * @param uniqueId defines the light's unique id
  26883. * @return the light or null if none found.
  26884. */
  26885. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26886. for (var index = 0; index < this.lights.length; index++) {
  26887. if (this.lights[index].uniqueId === uniqueId) {
  26888. return this.lights[index];
  26889. }
  26890. }
  26891. return null;
  26892. };
  26893. /**
  26894. * Gets a particle system by id
  26895. * @param id defines the particle system id
  26896. * @return the corresponding system or null if none found
  26897. */
  26898. Scene.prototype.getParticleSystemByID = function (id) {
  26899. for (var index = 0; index < this.particleSystems.length; index++) {
  26900. if (this.particleSystems[index].id === id) {
  26901. return this.particleSystems[index];
  26902. }
  26903. }
  26904. return null;
  26905. };
  26906. /**
  26907. * Gets a geometry using its ID
  26908. * @param id defines the geometry's id
  26909. * @return the geometry or null if none found.
  26910. */
  26911. Scene.prototype.getGeometryByID = function (id) {
  26912. for (var index = 0; index < this._geometries.length; index++) {
  26913. if (this._geometries[index].id === id) {
  26914. return this._geometries[index];
  26915. }
  26916. }
  26917. return null;
  26918. };
  26919. /**
  26920. * Add a new geometry to this scene
  26921. * @param geometry defines the geometry to be added to the scene.
  26922. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26923. * @return a boolean defining if the geometry was added or not
  26924. */
  26925. Scene.prototype.pushGeometry = function (geometry, force) {
  26926. if (!force && this.getGeometryByID(geometry.id)) {
  26927. return false;
  26928. }
  26929. this._geometries.push(geometry);
  26930. //notify the collision coordinator
  26931. if (this.collisionCoordinator) {
  26932. this.collisionCoordinator.onGeometryAdded(geometry);
  26933. }
  26934. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26935. return true;
  26936. };
  26937. /**
  26938. * Removes an existing geometry
  26939. * @param geometry defines the geometry to be removed from the scene
  26940. * @return a boolean defining if the geometry was removed or not
  26941. */
  26942. Scene.prototype.removeGeometry = function (geometry) {
  26943. var index = this._geometries.indexOf(geometry);
  26944. if (index > -1) {
  26945. this._geometries.splice(index, 1);
  26946. //notify the collision coordinator
  26947. if (this.collisionCoordinator) {
  26948. this.collisionCoordinator.onGeometryDeleted(geometry);
  26949. }
  26950. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26951. return true;
  26952. }
  26953. return false;
  26954. };
  26955. /**
  26956. * Gets the list of geometries attached to the scene
  26957. * @returns an array of Geometry
  26958. */
  26959. Scene.prototype.getGeometries = function () {
  26960. return this._geometries;
  26961. };
  26962. /**
  26963. * Gets the first added mesh found of a given ID
  26964. * @param id defines the id to search for
  26965. * @return the mesh found or null if not found at all
  26966. */
  26967. Scene.prototype.getMeshByID = function (id) {
  26968. for (var index = 0; index < this.meshes.length; index++) {
  26969. if (this.meshes[index].id === id) {
  26970. return this.meshes[index];
  26971. }
  26972. }
  26973. return null;
  26974. };
  26975. /**
  26976. * Gets a list of meshes using their id
  26977. * @param id defines the id to search for
  26978. * @returns a list of meshes
  26979. */
  26980. Scene.prototype.getMeshesByID = function (id) {
  26981. return this.meshes.filter(function (m) {
  26982. return m.id === id;
  26983. });
  26984. };
  26985. /**
  26986. * Gets the first added transform node found of a given ID
  26987. * @param id defines the id to search for
  26988. * @return the found transform node or null if not found at all.
  26989. */
  26990. Scene.prototype.getTransformNodeByID = function (id) {
  26991. for (var index = 0; index < this.transformNodes.length; index++) {
  26992. if (this.transformNodes[index].id === id) {
  26993. return this.transformNodes[index];
  26994. }
  26995. }
  26996. return null;
  26997. };
  26998. /**
  26999. * Gets a list of transform nodes using their id
  27000. * @param id defines the id to search for
  27001. * @returns a list of transform nodes
  27002. */
  27003. Scene.prototype.getTransformNodesByID = function (id) {
  27004. return this.transformNodes.filter(function (m) {
  27005. return m.id === id;
  27006. });
  27007. };
  27008. /**
  27009. * Gets a mesh with its auto-generated unique id
  27010. * @param uniqueId defines the unique id to search for
  27011. * @return the found mesh or null if not found at all.
  27012. */
  27013. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27014. for (var index = 0; index < this.meshes.length; index++) {
  27015. if (this.meshes[index].uniqueId === uniqueId) {
  27016. return this.meshes[index];
  27017. }
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * Gets a the last added mesh using a given id
  27023. * @param id defines the id to search for
  27024. * @return the found mesh or null if not found at all.
  27025. */
  27026. Scene.prototype.getLastMeshByID = function (id) {
  27027. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27028. if (this.meshes[index].id === id) {
  27029. return this.meshes[index];
  27030. }
  27031. }
  27032. return null;
  27033. };
  27034. /**
  27035. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27036. * @param id defines the id to search for
  27037. * @return the found node or null if not found at all
  27038. */
  27039. Scene.prototype.getLastEntryByID = function (id) {
  27040. var index;
  27041. for (index = this.meshes.length - 1; index >= 0; index--) {
  27042. if (this.meshes[index].id === id) {
  27043. return this.meshes[index];
  27044. }
  27045. }
  27046. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27047. if (this.transformNodes[index].id === id) {
  27048. return this.transformNodes[index];
  27049. }
  27050. }
  27051. for (index = this.cameras.length - 1; index >= 0; index--) {
  27052. if (this.cameras[index].id === id) {
  27053. return this.cameras[index];
  27054. }
  27055. }
  27056. for (index = this.lights.length - 1; index >= 0; index--) {
  27057. if (this.lights[index].id === id) {
  27058. return this.lights[index];
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. /**
  27064. * Gets a node (Mesh, Camera, Light) using a given id
  27065. * @param id defines the id to search for
  27066. * @return the found node or null if not found at all
  27067. */
  27068. Scene.prototype.getNodeByID = function (id) {
  27069. var mesh = this.getMeshByID(id);
  27070. if (mesh) {
  27071. return mesh;
  27072. }
  27073. var light = this.getLightByID(id);
  27074. if (light) {
  27075. return light;
  27076. }
  27077. var camera = this.getCameraByID(id);
  27078. if (camera) {
  27079. return camera;
  27080. }
  27081. var bone = this.getBoneByID(id);
  27082. return bone;
  27083. };
  27084. /**
  27085. * Gets a node (Mesh, Camera, Light) using a given name
  27086. * @param name defines the name to search for
  27087. * @return the found node or null if not found at all.
  27088. */
  27089. Scene.prototype.getNodeByName = function (name) {
  27090. var mesh = this.getMeshByName(name);
  27091. if (mesh) {
  27092. return mesh;
  27093. }
  27094. var light = this.getLightByName(name);
  27095. if (light) {
  27096. return light;
  27097. }
  27098. var camera = this.getCameraByName(name);
  27099. if (camera) {
  27100. return camera;
  27101. }
  27102. var bone = this.getBoneByName(name);
  27103. return bone;
  27104. };
  27105. /**
  27106. * Gets a mesh using a given name
  27107. * @param name defines the name to search for
  27108. * @return the found mesh or null if not found at all.
  27109. */
  27110. Scene.prototype.getMeshByName = function (name) {
  27111. for (var index = 0; index < this.meshes.length; index++) {
  27112. if (this.meshes[index].name === name) {
  27113. return this.meshes[index];
  27114. }
  27115. }
  27116. return null;
  27117. };
  27118. /**
  27119. * Gets a transform node using a given name
  27120. * @param name defines the name to search for
  27121. * @return the found transform node or null if not found at all.
  27122. */
  27123. Scene.prototype.getTransformNodeByName = function (name) {
  27124. for (var index = 0; index < this.transformNodes.length; index++) {
  27125. if (this.transformNodes[index].name === name) {
  27126. return this.transformNodes[index];
  27127. }
  27128. }
  27129. return null;
  27130. };
  27131. /**
  27132. * Gets a sound using a given name
  27133. * @param name defines the name to search for
  27134. * @return the found sound or null if not found at all.
  27135. */
  27136. Scene.prototype.getSoundByName = function (name) {
  27137. var index;
  27138. if (BABYLON.AudioEngine) {
  27139. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27140. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27141. return this.mainSoundTrack.soundCollection[index];
  27142. }
  27143. }
  27144. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27145. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27146. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27147. return this.soundTracks[sdIndex].soundCollection[index];
  27148. }
  27149. }
  27150. }
  27151. }
  27152. return null;
  27153. };
  27154. /**
  27155. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27156. * @param id defines the id to search for
  27157. * @return the found skeleton or null if not found at all.
  27158. */
  27159. Scene.prototype.getLastSkeletonByID = function (id) {
  27160. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27161. if (this.skeletons[index].id === id) {
  27162. return this.skeletons[index];
  27163. }
  27164. }
  27165. return null;
  27166. };
  27167. /**
  27168. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27169. * @param id defines the id to search for
  27170. * @return the found skeleton or null if not found at all.
  27171. */
  27172. Scene.prototype.getSkeletonById = function (id) {
  27173. for (var index = 0; index < this.skeletons.length; index++) {
  27174. if (this.skeletons[index].id === id) {
  27175. return this.skeletons[index];
  27176. }
  27177. }
  27178. return null;
  27179. };
  27180. /**
  27181. * Gets a skeleton using a given name
  27182. * @param name defines the name to search for
  27183. * @return the found skeleton or null if not found at all.
  27184. */
  27185. Scene.prototype.getSkeletonByName = function (name) {
  27186. for (var index = 0; index < this.skeletons.length; index++) {
  27187. if (this.skeletons[index].name === name) {
  27188. return this.skeletons[index];
  27189. }
  27190. }
  27191. return null;
  27192. };
  27193. /**
  27194. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27195. * @param id defines the id to search for
  27196. * @return the found morph target manager or null if not found at all.
  27197. */
  27198. Scene.prototype.getMorphTargetManagerById = function (id) {
  27199. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27200. if (this.morphTargetManagers[index].uniqueId === id) {
  27201. return this.morphTargetManagers[index];
  27202. }
  27203. }
  27204. return null;
  27205. };
  27206. /**
  27207. * Gets a boolean indicating if the given mesh is active
  27208. * @param mesh defines the mesh to look for
  27209. * @returns true if the mesh is in the active list
  27210. */
  27211. Scene.prototype.isActiveMesh = function (mesh) {
  27212. return (this._activeMeshes.indexOf(mesh) !== -1);
  27213. };
  27214. /**
  27215. * Return a the first highlight layer of the scene with a given name.
  27216. * @param name The name of the highlight layer to look for.
  27217. * @return The highlight layer if found otherwise null.
  27218. */
  27219. Scene.prototype.getHighlightLayerByName = function (name) {
  27220. for (var index = 0; index < this.effectLayers.length; index++) {
  27221. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27222. return this.effectLayers[index];
  27223. }
  27224. }
  27225. return null;
  27226. };
  27227. /**
  27228. * Return a the first highlight layer of the scene with a given name.
  27229. * @param name The name of the highlight layer to look for.
  27230. * @return The highlight layer if found otherwise null.
  27231. */
  27232. Scene.prototype.getGlowLayerByName = function (name) {
  27233. for (var index = 0; index < this.effectLayers.length; index++) {
  27234. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27235. return this.effectLayers[index];
  27236. }
  27237. }
  27238. return null;
  27239. };
  27240. Object.defineProperty(Scene.prototype, "uid", {
  27241. /**
  27242. * Return a unique id as a string which can serve as an identifier for the scene
  27243. */
  27244. get: function () {
  27245. if (!this._uid) {
  27246. this._uid = BABYLON.Tools.RandomId();
  27247. }
  27248. return this._uid;
  27249. },
  27250. enumerable: true,
  27251. configurable: true
  27252. });
  27253. /**
  27254. * Add an externaly attached data from its key.
  27255. * This method call will fail and return false, if such key already exists.
  27256. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27257. * @param key the unique key that identifies the data
  27258. * @param data the data object to associate to the key for this Engine instance
  27259. * @return true if no such key were already present and the data was added successfully, false otherwise
  27260. */
  27261. Scene.prototype.addExternalData = function (key, data) {
  27262. if (!this._externalData) {
  27263. this._externalData = new BABYLON.StringDictionary();
  27264. }
  27265. return this._externalData.add(key, data);
  27266. };
  27267. /**
  27268. * Get an externaly attached data from its key
  27269. * @param key the unique key that identifies the data
  27270. * @return the associated data, if present (can be null), or undefined if not present
  27271. */
  27272. Scene.prototype.getExternalData = function (key) {
  27273. if (!this._externalData) {
  27274. return null;
  27275. }
  27276. return this._externalData.get(key);
  27277. };
  27278. /**
  27279. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27280. * @param key the unique key that identifies the data
  27281. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27282. * @return the associated data, can be null if the factory returned null.
  27283. */
  27284. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27285. if (!this._externalData) {
  27286. this._externalData = new BABYLON.StringDictionary();
  27287. }
  27288. return this._externalData.getOrAddWithFactory(key, factory);
  27289. };
  27290. /**
  27291. * Remove an externaly attached data from the Engine instance
  27292. * @param key the unique key that identifies the data
  27293. * @return true if the data was successfully removed, false if it doesn't exist
  27294. */
  27295. Scene.prototype.removeExternalData = function (key) {
  27296. return this._externalData.remove(key);
  27297. };
  27298. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27299. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27300. if (mesh.showSubMeshesBoundingBox) {
  27301. var boundingInfo = subMesh.getBoundingInfo();
  27302. if (boundingInfo !== null && boundingInfo !== undefined) {
  27303. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27304. }
  27305. }
  27306. var material = subMesh.getMaterial();
  27307. if (material !== null && material !== undefined) {
  27308. // Render targets
  27309. if (material.getRenderTargetTextures !== undefined) {
  27310. if (this._processedMaterials.indexOf(material) === -1) {
  27311. this._processedMaterials.push(material);
  27312. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27313. }
  27314. }
  27315. // Dispatch
  27316. this._activeIndices.addCount(subMesh.indexCount, false);
  27317. this._renderingManager.dispatch(subMesh, mesh, material);
  27318. }
  27319. }
  27320. };
  27321. /**
  27322. * Clear the processed materials smart array preventing retention point in material dispose.
  27323. */
  27324. Scene.prototype.freeProcessedMaterials = function () {
  27325. this._processedMaterials.dispose();
  27326. };
  27327. /**
  27328. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27329. */
  27330. Scene.prototype.freeActiveMeshes = function () {
  27331. this._activeMeshes.dispose();
  27332. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27333. this.activeCamera._activeMeshes.dispose();
  27334. }
  27335. if (this.activeCameras) {
  27336. for (var i = 0; i < this.activeCameras.length; i++) {
  27337. var activeCamera = this.activeCameras[i];
  27338. if (activeCamera && activeCamera._activeMeshes) {
  27339. activeCamera._activeMeshes.dispose();
  27340. }
  27341. }
  27342. }
  27343. };
  27344. /**
  27345. * Clear the info related to rendering groups preventing retention points during dispose.
  27346. */
  27347. Scene.prototype.freeRenderingGroups = function () {
  27348. if (this._renderingManager) {
  27349. this._renderingManager.freeRenderingGroups();
  27350. }
  27351. if (this.textures) {
  27352. for (var i = 0; i < this.textures.length; i++) {
  27353. var texture = this.textures[i];
  27354. if (texture && texture.renderList) {
  27355. texture.freeRenderingGroups();
  27356. }
  27357. }
  27358. }
  27359. };
  27360. /** @hidden */
  27361. Scene.prototype._isInIntermediateRendering = function () {
  27362. return this._intermediateRendering;
  27363. };
  27364. /**
  27365. * Defines the current active mesh candidate provider
  27366. * @param provider defines the provider to use
  27367. */
  27368. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27369. this._activeMeshCandidateProvider = provider;
  27370. };
  27371. /**
  27372. * Gets the current active mesh candidate provider
  27373. * @returns the current active mesh candidate provider
  27374. */
  27375. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27376. return this._activeMeshCandidateProvider;
  27377. };
  27378. /**
  27379. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27380. * @returns the current scene
  27381. */
  27382. Scene.prototype.freezeActiveMeshes = function () {
  27383. if (!this.activeCamera) {
  27384. return this;
  27385. }
  27386. if (!this._frustumPlanes) {
  27387. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27388. }
  27389. this._evaluateActiveMeshes();
  27390. this._activeMeshesFrozen = true;
  27391. return this;
  27392. };
  27393. /**
  27394. * Use this function to restart evaluating active meshes on every frame
  27395. * @returns the current scene
  27396. */
  27397. Scene.prototype.unfreezeActiveMeshes = function () {
  27398. this._activeMeshesFrozen = false;
  27399. return this;
  27400. };
  27401. Scene.prototype._evaluateActiveMeshes = function () {
  27402. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27403. return;
  27404. }
  27405. if (!this.activeCamera) {
  27406. return;
  27407. }
  27408. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27409. this.activeCamera._activeMeshes.reset();
  27410. this._activeMeshes.reset();
  27411. this._renderingManager.reset();
  27412. this._processedMaterials.reset();
  27413. this._activeParticleSystems.reset();
  27414. this._activeSkeletons.reset();
  27415. this._softwareSkinnedMeshes.reset();
  27416. if (this._boundingBoxRenderer) {
  27417. this._boundingBoxRenderer.reset();
  27418. }
  27419. // Meshes
  27420. var meshes;
  27421. var len;
  27422. var checkIsEnabled = true;
  27423. // Determine mesh candidates
  27424. if (this._activeMeshCandidateProvider !== undefined) {
  27425. // Use _activeMeshCandidateProvider
  27426. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27427. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27428. if (meshes !== undefined) {
  27429. len = meshes.length;
  27430. }
  27431. else {
  27432. len = 0;
  27433. }
  27434. }
  27435. else if (this._selectionOctree !== undefined) {
  27436. // Octree
  27437. var selection = this._selectionOctree.select(this._frustumPlanes);
  27438. meshes = selection.data;
  27439. len = selection.length;
  27440. }
  27441. else {
  27442. // Full scene traversal
  27443. len = this.meshes.length;
  27444. meshes = this.meshes;
  27445. }
  27446. // Check each mesh
  27447. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27448. mesh = meshes[meshIndex];
  27449. if (mesh.isBlocked) {
  27450. continue;
  27451. }
  27452. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27453. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27454. continue;
  27455. }
  27456. mesh.computeWorldMatrix();
  27457. // Intersections
  27458. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27459. this._meshesForIntersections.pushNoDuplicate(mesh);
  27460. }
  27461. // Switch to current LOD
  27462. meshLOD = mesh.getLOD(this.activeCamera);
  27463. if (meshLOD === undefined || meshLOD === null) {
  27464. continue;
  27465. }
  27466. mesh._preActivate();
  27467. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27468. this._activeMeshes.push(mesh);
  27469. this.activeCamera._activeMeshes.push(mesh);
  27470. mesh._activate(this._renderId);
  27471. if (meshLOD !== mesh) {
  27472. meshLOD._activate(this._renderId);
  27473. }
  27474. this._activeMesh(mesh, meshLOD);
  27475. }
  27476. }
  27477. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27478. // Particle systems
  27479. if (this.particlesEnabled) {
  27480. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27481. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27482. var particleSystem = this.particleSystems[particleIndex];
  27483. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27484. continue;
  27485. }
  27486. var emitter = particleSystem.emitter;
  27487. if (!emitter.position || emitter.isEnabled()) {
  27488. this._activeParticleSystems.push(particleSystem);
  27489. particleSystem.animate();
  27490. this._renderingManager.dispatchParticles(particleSystem);
  27491. }
  27492. }
  27493. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27494. }
  27495. };
  27496. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27497. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27498. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27499. mesh.skeleton.prepare();
  27500. }
  27501. if (!mesh.computeBonesUsingShaders) {
  27502. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27503. }
  27504. }
  27505. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27506. var boundingInfo = sourceMesh.getBoundingInfo();
  27507. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27508. }
  27509. if (mesh !== undefined && mesh !== null
  27510. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27511. // Submeshes Octrees
  27512. var len;
  27513. var subMeshes;
  27514. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27515. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27516. len = intersections.length;
  27517. subMeshes = intersections.data;
  27518. }
  27519. else {
  27520. subMeshes = mesh.subMeshes;
  27521. len = subMeshes.length;
  27522. }
  27523. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27524. subMesh = subMeshes[subIndex];
  27525. this._evaluateSubMesh(subMesh, mesh);
  27526. }
  27527. }
  27528. };
  27529. /**
  27530. * Update the transform matrix to update from the current active camera
  27531. * @param force defines a boolean used to force the update even if cache is up to date
  27532. */
  27533. Scene.prototype.updateTransformMatrix = function (force) {
  27534. if (!this.activeCamera) {
  27535. return;
  27536. }
  27537. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27538. };
  27539. /**
  27540. * 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)
  27541. * @param alternateCamera defines the camera to use
  27542. */
  27543. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27544. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27545. };
  27546. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27547. if (camera && camera._skipRendering) {
  27548. return;
  27549. }
  27550. var engine = this._engine;
  27551. this.activeCamera = camera;
  27552. if (!this.activeCamera)
  27553. throw new Error("Active camera not set");
  27554. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27555. // Viewport
  27556. engine.setViewport(this.activeCamera.viewport);
  27557. // Camera
  27558. this.resetCachedMaterial();
  27559. this._renderId++;
  27560. this.updateTransformMatrix();
  27561. if (camera._alternateCamera) {
  27562. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27563. this._alternateRendering = true;
  27564. }
  27565. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27566. // Meshes
  27567. this._evaluateActiveMeshes();
  27568. // Software skinning
  27569. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27570. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27571. mesh.applySkeleton(mesh.skeleton);
  27572. }
  27573. // Render targets
  27574. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27575. var needsRestoreFrameBuffer = false;
  27576. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27577. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27578. }
  27579. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27580. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27581. }
  27582. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27583. this._intermediateRendering = true;
  27584. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27585. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27586. var renderTarget = this._renderTargets.data[renderIndex];
  27587. if (renderTarget._shouldRender()) {
  27588. this._renderId++;
  27589. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27590. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27591. }
  27592. }
  27593. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27594. this._intermediateRendering = false;
  27595. this._renderId++;
  27596. needsRestoreFrameBuffer = true; // Restore back buffer
  27597. }
  27598. // Render EffecttLayer Texture
  27599. var stencilState = this._engine.getStencilBuffer();
  27600. var renderEffects = false;
  27601. var needStencil = false;
  27602. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27603. this._intermediateRendering = true;
  27604. for (var i = 0; i < this.effectLayers.length; i++) {
  27605. var effectLayer = this.effectLayers[i];
  27606. if (effectLayer.shouldRender() &&
  27607. (!effectLayer.camera ||
  27608. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27609. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27610. renderEffects = true;
  27611. needStencil = needStencil || effectLayer.needStencil();
  27612. var renderTarget = effectLayer._mainTexture;
  27613. if (renderTarget._shouldRender()) {
  27614. this._renderId++;
  27615. renderTarget.render(false, false);
  27616. needsRestoreFrameBuffer = true;
  27617. }
  27618. }
  27619. }
  27620. this._intermediateRendering = false;
  27621. this._renderId++;
  27622. }
  27623. if (needsRestoreFrameBuffer) {
  27624. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27625. }
  27626. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27627. // Prepare Frame
  27628. this.postProcessManager._prepareFrame();
  27629. // Backgrounds
  27630. var layerIndex;
  27631. var layer;
  27632. if (this.layers.length) {
  27633. engine.setDepthBuffer(false);
  27634. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27635. layer = this.layers[layerIndex];
  27636. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27637. layer.render();
  27638. }
  27639. }
  27640. engine.setDepthBuffer(true);
  27641. }
  27642. // Activate effect Layer stencil
  27643. if (needStencil) {
  27644. this._engine.setStencilBuffer(true);
  27645. }
  27646. // Render
  27647. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27648. this._renderingManager.render(null, null, true, true);
  27649. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27650. // Restore effect Layer stencil
  27651. if (needStencil) {
  27652. this._engine.setStencilBuffer(stencilState);
  27653. }
  27654. // Bounding boxes
  27655. if (this._boundingBoxRenderer) {
  27656. this._boundingBoxRenderer.render();
  27657. }
  27658. // Lens flares
  27659. if (this.lensFlaresEnabled) {
  27660. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27661. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27662. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27663. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27664. lensFlareSystem.render();
  27665. }
  27666. }
  27667. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27668. }
  27669. // Effect Layer
  27670. if (renderEffects) {
  27671. engine.setDepthBuffer(false);
  27672. for (var i = 0; i < this.effectLayers.length; i++) {
  27673. if (this.effectLayers[i].shouldRender()) {
  27674. this.effectLayers[i].render();
  27675. }
  27676. }
  27677. engine.setDepthBuffer(true);
  27678. }
  27679. // Foregrounds
  27680. if (this.layers.length) {
  27681. engine.setDepthBuffer(false);
  27682. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27683. layer = this.layers[layerIndex];
  27684. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27685. layer.render();
  27686. }
  27687. }
  27688. engine.setDepthBuffer(true);
  27689. }
  27690. // Finalize frame
  27691. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27692. // Reset some special arrays
  27693. this._renderTargets.reset();
  27694. this._alternateRendering = false;
  27695. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27696. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27697. };
  27698. Scene.prototype._processSubCameras = function (camera) {
  27699. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27700. this._renderForCamera(camera);
  27701. return;
  27702. }
  27703. // rig cameras
  27704. for (var index = 0; index < camera._rigCameras.length; index++) {
  27705. this._renderForCamera(camera._rigCameras[index], camera);
  27706. }
  27707. this.activeCamera = camera;
  27708. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27709. };
  27710. Scene.prototype._checkIntersections = function () {
  27711. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27712. var sourceMesh = this._meshesForIntersections.data[index];
  27713. if (!sourceMesh.actionManager) {
  27714. continue;
  27715. }
  27716. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27717. var action = sourceMesh.actionManager.actions[actionIndex];
  27718. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27719. var parameters = action.getTriggerParameter();
  27720. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27721. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27722. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27723. if (areIntersecting && currentIntersectionInProgress === -1) {
  27724. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27725. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27726. sourceMesh._intersectionsInProgress.push(otherMesh);
  27727. }
  27728. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27729. sourceMesh._intersectionsInProgress.push(otherMesh);
  27730. }
  27731. }
  27732. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27733. //They intersected, and now they don't.
  27734. //is this trigger an exit trigger? execute an event.
  27735. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27736. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27737. }
  27738. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27739. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27740. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27741. return otherMesh === parameterMesh;
  27742. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27743. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27744. }
  27745. }
  27746. }
  27747. }
  27748. }
  27749. };
  27750. /**
  27751. * Render the scene
  27752. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27753. */
  27754. Scene.prototype.render = function (updateCameras) {
  27755. if (updateCameras === void 0) { updateCameras = true; }
  27756. if (this.isDisposed) {
  27757. return;
  27758. }
  27759. this._activeParticles.fetchNewFrame();
  27760. this._totalVertices.fetchNewFrame();
  27761. this._activeIndices.fetchNewFrame();
  27762. this._activeBones.fetchNewFrame();
  27763. this._meshesForIntersections.reset();
  27764. this.resetCachedMaterial();
  27765. this.onBeforeAnimationsObservable.notifyObservers(this);
  27766. // Actions
  27767. if (this.actionManager) {
  27768. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27769. }
  27770. //Simplification Queue
  27771. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27772. this.simplificationQueue.executeNext();
  27773. }
  27774. if (this._engine.isDeterministicLockStep()) {
  27775. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27776. var defaultFPS = (60.0 / 1000.0);
  27777. var defaultFrameTime = 1000 / 60; // frame time in MS
  27778. if (this._physicsEngine) {
  27779. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27780. }
  27781. var stepsTaken = 0;
  27782. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27783. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27784. internalSteps = Math.min(internalSteps, maxSubSteps);
  27785. do {
  27786. this.onBeforeStepObservable.notifyObservers(this);
  27787. // Animations
  27788. this._animationRatio = defaultFrameTime * defaultFPS;
  27789. this._animate();
  27790. this.onAfterAnimationsObservable.notifyObservers(this);
  27791. // Physics
  27792. if (this._physicsEngine) {
  27793. this.onBeforePhysicsObservable.notifyObservers(this);
  27794. this._physicsEngine._step(defaultFrameTime / 1000);
  27795. this.onAfterPhysicsObservable.notifyObservers(this);
  27796. }
  27797. this.onAfterStepObservable.notifyObservers(this);
  27798. this._currentStepId++;
  27799. stepsTaken++;
  27800. deltaTime -= defaultFrameTime;
  27801. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27802. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27803. }
  27804. else {
  27805. // Animations
  27806. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27807. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27808. this._animate();
  27809. this.onAfterAnimationsObservable.notifyObservers(this);
  27810. // Physics
  27811. if (this._physicsEngine) {
  27812. this.onBeforePhysicsObservable.notifyObservers(this);
  27813. this._physicsEngine._step(deltaTime / 1000.0);
  27814. this.onAfterPhysicsObservable.notifyObservers(this);
  27815. }
  27816. }
  27817. // update gamepad manager
  27818. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27819. this._gamepadManager._checkGamepadsStatus();
  27820. }
  27821. // Update Cameras
  27822. if (updateCameras) {
  27823. if (this.activeCameras.length > 0) {
  27824. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27825. var camera = this.activeCameras[cameraIndex];
  27826. camera.update();
  27827. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27828. // rig cameras
  27829. for (var index = 0; index < camera._rigCameras.length; index++) {
  27830. camera._rigCameras[index].update();
  27831. }
  27832. }
  27833. }
  27834. }
  27835. else if (this.activeCamera) {
  27836. this.activeCamera.update();
  27837. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27838. // rig cameras
  27839. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27840. this.activeCamera._rigCameras[index].update();
  27841. }
  27842. }
  27843. }
  27844. }
  27845. // Before render
  27846. this.onBeforeRenderObservable.notifyObservers(this);
  27847. // Customs render targets
  27848. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27849. var engine = this.getEngine();
  27850. var currentActiveCamera = this.activeCamera;
  27851. if (this.renderTargetsEnabled) {
  27852. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27853. this._intermediateRendering = true;
  27854. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27855. var renderTarget = this.customRenderTargets[customIndex];
  27856. if (renderTarget._shouldRender()) {
  27857. this._renderId++;
  27858. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27859. if (!this.activeCamera)
  27860. throw new Error("Active camera not set");
  27861. // Viewport
  27862. engine.setViewport(this.activeCamera.viewport);
  27863. // Camera
  27864. this.updateTransformMatrix();
  27865. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27866. }
  27867. }
  27868. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27869. this._intermediateRendering = false;
  27870. this._renderId++;
  27871. }
  27872. // Restore back buffer
  27873. if (this.customRenderTargets.length > 0) {
  27874. engine.restoreDefaultFramebuffer();
  27875. }
  27876. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27877. this.activeCamera = currentActiveCamera;
  27878. // Procedural textures
  27879. if (this.proceduralTexturesEnabled) {
  27880. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27881. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27882. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27883. if (proceduralTexture._shouldRender()) {
  27884. proceduralTexture.render();
  27885. }
  27886. }
  27887. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27888. }
  27889. // Clear
  27890. if (this.autoClearDepthAndStencil || this.autoClear) {
  27891. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27892. }
  27893. // Shadows
  27894. if (this.shadowsEnabled) {
  27895. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27896. var light = this.lights[lightIndex];
  27897. var shadowGenerator = light.getShadowGenerator();
  27898. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27899. var shadowMap = (shadowGenerator.getShadowMap());
  27900. if (this.textures.indexOf(shadowMap) !== -1) {
  27901. this._renderTargets.push(shadowMap);
  27902. }
  27903. }
  27904. }
  27905. }
  27906. // Depth renderer
  27907. for (var key in this._depthRenderer) {
  27908. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27909. }
  27910. // Geometry renderer
  27911. if (this._geometryBufferRenderer) {
  27912. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27913. }
  27914. // RenderPipeline
  27915. if (this._postProcessRenderPipelineManager) {
  27916. this._postProcessRenderPipelineManager.update();
  27917. }
  27918. // Multi-cameras?
  27919. if (this.activeCameras.length > 0) {
  27920. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27921. if (cameraIndex > 0) {
  27922. this._engine.clear(null, false, true, true);
  27923. }
  27924. this._processSubCameras(this.activeCameras[cameraIndex]);
  27925. }
  27926. }
  27927. else {
  27928. if (!this.activeCamera) {
  27929. throw new Error("No camera defined");
  27930. }
  27931. this._processSubCameras(this.activeCamera);
  27932. }
  27933. // Intersection checks
  27934. this._checkIntersections();
  27935. // Update the audio listener attached to the camera
  27936. if (BABYLON.AudioEngine) {
  27937. this._updateAudioParameters();
  27938. }
  27939. // After render
  27940. if (this.afterRender) {
  27941. this.afterRender();
  27942. }
  27943. this.onAfterRenderObservable.notifyObservers(this);
  27944. // Cleaning
  27945. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27946. var data = this._toBeDisposed.data[index];
  27947. if (data) {
  27948. data.dispose();
  27949. }
  27950. this._toBeDisposed[index] = null;
  27951. }
  27952. this._toBeDisposed.reset();
  27953. if (this.dumpNextRenderTargets) {
  27954. this.dumpNextRenderTargets = false;
  27955. }
  27956. this._activeBones.addCount(0, true);
  27957. this._activeIndices.addCount(0, true);
  27958. this._activeParticles.addCount(0, true);
  27959. };
  27960. Scene.prototype._updateAudioParameters = function () {
  27961. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27962. return;
  27963. }
  27964. var listeningCamera;
  27965. var audioEngine = BABYLON.Engine.audioEngine;
  27966. if (this.activeCameras.length > 0) {
  27967. listeningCamera = this.activeCameras[0];
  27968. }
  27969. else {
  27970. listeningCamera = this.activeCamera;
  27971. }
  27972. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27973. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27974. // for VR cameras
  27975. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27976. listeningCamera = listeningCamera.rigCameras[0];
  27977. }
  27978. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27979. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27980. cameraDirection.normalize();
  27981. // To avoid some errors on GearVR
  27982. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27983. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27984. }
  27985. var i;
  27986. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27987. var sound = this.mainSoundTrack.soundCollection[i];
  27988. if (sound.useCustomAttenuation) {
  27989. sound.updateDistanceFromListener();
  27990. }
  27991. }
  27992. for (i = 0; i < this.soundTracks.length; i++) {
  27993. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27994. sound = this.soundTracks[i].soundCollection[j];
  27995. if (sound.useCustomAttenuation) {
  27996. sound.updateDistanceFromListener();
  27997. }
  27998. }
  27999. }
  28000. }
  28001. };
  28002. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28003. // Audio
  28004. /**
  28005. * Gets or sets if audio support is enabled
  28006. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28007. */
  28008. get: function () {
  28009. return this._audioEnabled;
  28010. },
  28011. set: function (value) {
  28012. this._audioEnabled = value;
  28013. if (BABYLON.AudioEngine) {
  28014. if (this._audioEnabled) {
  28015. this._enableAudio();
  28016. }
  28017. else {
  28018. this._disableAudio();
  28019. }
  28020. }
  28021. },
  28022. enumerable: true,
  28023. configurable: true
  28024. });
  28025. Scene.prototype._disableAudio = function () {
  28026. var i;
  28027. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28028. this.mainSoundTrack.soundCollection[i].pause();
  28029. }
  28030. for (i = 0; i < this.soundTracks.length; i++) {
  28031. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28032. this.soundTracks[i].soundCollection[j].pause();
  28033. }
  28034. }
  28035. };
  28036. Scene.prototype._enableAudio = function () {
  28037. var i;
  28038. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28039. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28040. this.mainSoundTrack.soundCollection[i].play();
  28041. }
  28042. }
  28043. for (i = 0; i < this.soundTracks.length; i++) {
  28044. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28045. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28046. this.soundTracks[i].soundCollection[j].play();
  28047. }
  28048. }
  28049. }
  28050. };
  28051. Object.defineProperty(Scene.prototype, "headphone", {
  28052. /**
  28053. * Gets or sets if audio will be output to headphones
  28054. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28055. */
  28056. get: function () {
  28057. return this._headphone;
  28058. },
  28059. set: function (value) {
  28060. this._headphone = value;
  28061. if (BABYLON.AudioEngine) {
  28062. if (this._headphone) {
  28063. this._switchAudioModeForHeadphones();
  28064. }
  28065. else {
  28066. this._switchAudioModeForNormalSpeakers();
  28067. }
  28068. }
  28069. },
  28070. enumerable: true,
  28071. configurable: true
  28072. });
  28073. Scene.prototype._switchAudioModeForHeadphones = function () {
  28074. this.mainSoundTrack.switchPanningModelToHRTF();
  28075. for (var i = 0; i < this.soundTracks.length; i++) {
  28076. this.soundTracks[i].switchPanningModelToHRTF();
  28077. }
  28078. };
  28079. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28080. this.mainSoundTrack.switchPanningModelToEqualPower();
  28081. for (var i = 0; i < this.soundTracks.length; i++) {
  28082. this.soundTracks[i].switchPanningModelToEqualPower();
  28083. }
  28084. };
  28085. /**
  28086. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28087. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28088. * @returns the created depth renderer
  28089. */
  28090. Scene.prototype.enableDepthRenderer = function (camera) {
  28091. camera = camera || this.activeCamera;
  28092. if (!camera) {
  28093. throw "No camera available to enable depth renderer";
  28094. }
  28095. if (!this._depthRenderer[camera.id]) {
  28096. var textureType = 0;
  28097. if (this._engine.getCaps().textureHalfFloatRender) {
  28098. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28099. }
  28100. else if (this._engine.getCaps().textureFloatRender) {
  28101. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28102. }
  28103. else {
  28104. throw "Depth renderer does not support int texture type";
  28105. }
  28106. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28107. }
  28108. return this._depthRenderer[camera.id];
  28109. };
  28110. /**
  28111. * Disables a depth renderer for a given camera
  28112. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28113. */
  28114. Scene.prototype.disableDepthRenderer = function (camera) {
  28115. camera = camera || this.activeCamera;
  28116. if (!camera || !this._depthRenderer[camera.id]) {
  28117. return;
  28118. }
  28119. this._depthRenderer[camera.id].dispose();
  28120. delete this._depthRenderer[camera.id];
  28121. };
  28122. /**
  28123. * Enables a GeometryBufferRender and associates it with the scene
  28124. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28125. * @returns the GeometryBufferRenderer
  28126. */
  28127. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28128. if (ratio === void 0) { ratio = 1; }
  28129. if (this._geometryBufferRenderer) {
  28130. return this._geometryBufferRenderer;
  28131. }
  28132. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28133. if (!this._geometryBufferRenderer.isSupported) {
  28134. this._geometryBufferRenderer = null;
  28135. }
  28136. return this._geometryBufferRenderer;
  28137. };
  28138. /**
  28139. * Disables the GeometryBufferRender associated with the scene
  28140. */
  28141. Scene.prototype.disableGeometryBufferRenderer = function () {
  28142. if (!this._geometryBufferRenderer) {
  28143. return;
  28144. }
  28145. this._geometryBufferRenderer.dispose();
  28146. this._geometryBufferRenderer = null;
  28147. };
  28148. /**
  28149. * Freeze all materials
  28150. * A frozen material will not be updatable but should be faster to render
  28151. */
  28152. Scene.prototype.freezeMaterials = function () {
  28153. for (var i = 0; i < this.materials.length; i++) {
  28154. this.materials[i].freeze();
  28155. }
  28156. };
  28157. /**
  28158. * Unfreeze all materials
  28159. * A frozen material will not be updatable but should be faster to render
  28160. */
  28161. Scene.prototype.unfreezeMaterials = function () {
  28162. for (var i = 0; i < this.materials.length; i++) {
  28163. this.materials[i].unfreeze();
  28164. }
  28165. };
  28166. /**
  28167. * Releases all held ressources
  28168. */
  28169. Scene.prototype.dispose = function () {
  28170. this.beforeRender = null;
  28171. this.afterRender = null;
  28172. this.skeletons = [];
  28173. this.morphTargetManagers = [];
  28174. this.importedMeshesFiles = new Array();
  28175. this.stopAllAnimations();
  28176. this.resetCachedMaterial();
  28177. for (var key in this._depthRenderer) {
  28178. this._depthRenderer[key].dispose();
  28179. }
  28180. if (this._gamepadManager) {
  28181. this._gamepadManager.dispose();
  28182. this._gamepadManager = null;
  28183. }
  28184. // Smart arrays
  28185. if (this.activeCamera) {
  28186. this.activeCamera._activeMeshes.dispose();
  28187. this.activeCamera = null;
  28188. }
  28189. this._activeMeshes.dispose();
  28190. this._renderingManager.dispose();
  28191. this._processedMaterials.dispose();
  28192. this._activeParticleSystems.dispose();
  28193. this._activeSkeletons.dispose();
  28194. this._softwareSkinnedMeshes.dispose();
  28195. this._renderTargets.dispose();
  28196. this._registeredForLateAnimationBindings.dispose();
  28197. if (this._boundingBoxRenderer) {
  28198. this._boundingBoxRenderer.dispose();
  28199. }
  28200. this._meshesForIntersections.dispose();
  28201. this._toBeDisposed.dispose();
  28202. // Abort active requests
  28203. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28204. var request = _a[_i];
  28205. request.abort();
  28206. }
  28207. // Debug layer
  28208. if (this._debugLayer) {
  28209. this._debugLayer.hide();
  28210. }
  28211. // Events
  28212. this.onDisposeObservable.notifyObservers(this);
  28213. this.onDisposeObservable.clear();
  28214. this.onBeforeRenderObservable.clear();
  28215. this.onAfterRenderObservable.clear();
  28216. this.onBeforeRenderTargetsRenderObservable.clear();
  28217. this.onAfterRenderTargetsRenderObservable.clear();
  28218. this.onAfterStepObservable.clear();
  28219. this.onBeforeStepObservable.clear();
  28220. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28221. this.onAfterActiveMeshesEvaluationObservable.clear();
  28222. this.onBeforeParticlesRenderingObservable.clear();
  28223. this.onAfterParticlesRenderingObservable.clear();
  28224. this.onBeforeSpritesRenderingObservable.clear();
  28225. this.onAfterSpritesRenderingObservable.clear();
  28226. this.onBeforeDrawPhaseObservable.clear();
  28227. this.onAfterDrawPhaseObservable.clear();
  28228. this.onBeforePhysicsObservable.clear();
  28229. this.onAfterPhysicsObservable.clear();
  28230. this.onBeforeAnimationsObservable.clear();
  28231. this.onAfterAnimationsObservable.clear();
  28232. this.onDataLoadedObservable.clear();
  28233. this.detachControl();
  28234. // Release sounds & sounds tracks
  28235. if (BABYLON.AudioEngine) {
  28236. this.disposeSounds();
  28237. }
  28238. // VR Helper
  28239. if (this.VRHelper) {
  28240. this.VRHelper.dispose();
  28241. }
  28242. // Detach cameras
  28243. var canvas = this._engine.getRenderingCanvas();
  28244. if (canvas) {
  28245. var index;
  28246. for (index = 0; index < this.cameras.length; index++) {
  28247. this.cameras[index].detachControl(canvas);
  28248. }
  28249. }
  28250. // Release animation groups
  28251. while (this.animationGroups.length) {
  28252. this.animationGroups[0].dispose();
  28253. }
  28254. // Release lights
  28255. while (this.lights.length) {
  28256. this.lights[0].dispose();
  28257. }
  28258. // Release meshes
  28259. while (this.meshes.length) {
  28260. this.meshes[0].dispose(true);
  28261. }
  28262. while (this.transformNodes.length) {
  28263. this.removeTransformNode(this.transformNodes[0]);
  28264. }
  28265. // Release cameras
  28266. while (this.cameras.length) {
  28267. this.cameras[0].dispose();
  28268. }
  28269. // Release materials
  28270. if (this.defaultMaterial) {
  28271. this.defaultMaterial.dispose();
  28272. }
  28273. while (this.multiMaterials.length) {
  28274. this.multiMaterials[0].dispose();
  28275. }
  28276. while (this.materials.length) {
  28277. this.materials[0].dispose();
  28278. }
  28279. // Release particles
  28280. while (this.particleSystems.length) {
  28281. this.particleSystems[0].dispose();
  28282. }
  28283. // Release sprites
  28284. while (this.spriteManagers.length) {
  28285. this.spriteManagers[0].dispose();
  28286. }
  28287. // Release postProcesses
  28288. while (this.postProcesses.length) {
  28289. this.postProcesses[0].dispose();
  28290. }
  28291. // Release layers
  28292. while (this.layers.length) {
  28293. this.layers[0].dispose();
  28294. }
  28295. while (this.effectLayers.length) {
  28296. this.effectLayers[0].dispose();
  28297. }
  28298. // Release textures
  28299. while (this.textures.length) {
  28300. this.textures[0].dispose();
  28301. }
  28302. // Release UBO
  28303. this._sceneUbo.dispose();
  28304. if (this._alternateSceneUbo) {
  28305. this._alternateSceneUbo.dispose();
  28306. }
  28307. // Post-processes
  28308. this.postProcessManager.dispose();
  28309. if (this._postProcessRenderPipelineManager) {
  28310. this._postProcessRenderPipelineManager.dispose();
  28311. }
  28312. // Physics
  28313. if (this._physicsEngine) {
  28314. this.disablePhysicsEngine();
  28315. }
  28316. // Remove from engine
  28317. index = this._engine.scenes.indexOf(this);
  28318. if (index > -1) {
  28319. this._engine.scenes.splice(index, 1);
  28320. }
  28321. this._engine.wipeCaches(true);
  28322. this._isDisposed = true;
  28323. };
  28324. Object.defineProperty(Scene.prototype, "isDisposed", {
  28325. /**
  28326. * Gets if the scene is already disposed
  28327. */
  28328. get: function () {
  28329. return this._isDisposed;
  28330. },
  28331. enumerable: true,
  28332. configurable: true
  28333. });
  28334. /**
  28335. * Releases sounds & soundtracks
  28336. */
  28337. Scene.prototype.disposeSounds = function () {
  28338. if (!this._mainSoundTrack) {
  28339. return;
  28340. }
  28341. this.mainSoundTrack.dispose();
  28342. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28343. this.soundTracks[scIndex].dispose();
  28344. }
  28345. };
  28346. /**
  28347. * Call this function to reduce memory footprint of the scene.
  28348. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28349. */
  28350. Scene.prototype.clearCachedVertexData = function () {
  28351. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28352. var mesh = this.meshes[meshIndex];
  28353. var geometry = mesh.geometry;
  28354. if (geometry) {
  28355. geometry._indices = [];
  28356. for (var vbName in geometry._vertexBuffers) {
  28357. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28358. continue;
  28359. }
  28360. geometry._vertexBuffers[vbName]._buffer._data = null;
  28361. }
  28362. }
  28363. }
  28364. };
  28365. /**
  28366. * This function will remove the local cached buffer data from texture.
  28367. * It will save memory but will prevent the texture from being rebuilt
  28368. */
  28369. Scene.prototype.cleanCachedTextureBuffer = function () {
  28370. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28371. var baseTexture = _a[_i];
  28372. var buffer = baseTexture._buffer;
  28373. if (buffer) {
  28374. baseTexture._buffer = null;
  28375. }
  28376. }
  28377. };
  28378. // Octrees
  28379. /**
  28380. * Get the world extend vectors with an optional filter
  28381. *
  28382. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28383. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28384. */
  28385. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28386. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28387. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28388. filterPredicate = filterPredicate || (function () { return true; });
  28389. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28390. mesh.computeWorldMatrix(true);
  28391. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28392. return;
  28393. }
  28394. var boundingInfo = mesh.getBoundingInfo();
  28395. var minBox = boundingInfo.boundingBox.minimumWorld;
  28396. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28397. BABYLON.Tools.CheckExtends(minBox, min, max);
  28398. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28399. });
  28400. return {
  28401. min: min,
  28402. max: max
  28403. };
  28404. };
  28405. /**
  28406. * Creates or updates the octree used to boost selection (picking)
  28407. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28408. * @param maxCapacity defines the maximum capacity per leaf
  28409. * @param maxDepth defines the maximum depth of the octree
  28410. * @returns an octree of AbstractMesh
  28411. */
  28412. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28413. if (maxCapacity === void 0) { maxCapacity = 64; }
  28414. if (maxDepth === void 0) { maxDepth = 2; }
  28415. if (!this._selectionOctree) {
  28416. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28417. }
  28418. var worldExtends = this.getWorldExtends();
  28419. // Update octree
  28420. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28421. return this._selectionOctree;
  28422. };
  28423. // Picking
  28424. /**
  28425. * Creates a ray that can be used to pick in the scene
  28426. * @param x defines the x coordinate of the origin (on-screen)
  28427. * @param y defines the y coordinate of the origin (on-screen)
  28428. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28429. * @param camera defines the camera to use for the picking
  28430. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28431. * @returns a Ray
  28432. */
  28433. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28434. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28435. var result = BABYLON.Ray.Zero();
  28436. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28437. return result;
  28438. };
  28439. /**
  28440. * Creates a ray that can be used to pick in the scene
  28441. * @param x defines the x coordinate of the origin (on-screen)
  28442. * @param y defines the y coordinate of the origin (on-screen)
  28443. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28444. * @param result defines the ray where to store the picking ray
  28445. * @param camera defines the camera to use for the picking
  28446. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28447. * @returns the current scene
  28448. */
  28449. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28450. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28451. var engine = this._engine;
  28452. if (!camera) {
  28453. if (!this.activeCamera)
  28454. throw new Error("Active camera not set");
  28455. camera = this.activeCamera;
  28456. }
  28457. var cameraViewport = camera.viewport;
  28458. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28459. // Moving coordinates to local viewport world
  28460. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28461. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28462. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28463. return this;
  28464. };
  28465. /**
  28466. * Creates a ray that can be used to pick in the scene
  28467. * @param x defines the x coordinate of the origin (on-screen)
  28468. * @param y defines the y coordinate of the origin (on-screen)
  28469. * @param camera defines the camera to use for the picking
  28470. * @returns a Ray
  28471. */
  28472. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28473. var result = BABYLON.Ray.Zero();
  28474. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28475. return result;
  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 result defines the ray where to store the picking ray
  28482. * @param camera defines the camera to use for the picking
  28483. * @returns the current scene
  28484. */
  28485. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28486. if (!BABYLON.PickingInfo) {
  28487. return this;
  28488. }
  28489. var engine = this._engine;
  28490. if (!camera) {
  28491. if (!this.activeCamera)
  28492. throw new Error("Active camera not set");
  28493. camera = this.activeCamera;
  28494. }
  28495. var cameraViewport = camera.viewport;
  28496. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28497. var identity = BABYLON.Matrix.Identity();
  28498. // Moving coordinates to local viewport world
  28499. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28500. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28501. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28502. return this;
  28503. };
  28504. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28505. if (!BABYLON.PickingInfo) {
  28506. return null;
  28507. }
  28508. var pickingInfo = null;
  28509. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28510. var mesh = this.meshes[meshIndex];
  28511. if (predicate) {
  28512. if (!predicate(mesh)) {
  28513. continue;
  28514. }
  28515. }
  28516. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28517. continue;
  28518. }
  28519. var world = mesh.getWorldMatrix();
  28520. var ray = rayFunction(world);
  28521. var result = mesh.intersects(ray, fastCheck);
  28522. if (!result || !result.hit)
  28523. continue;
  28524. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28525. continue;
  28526. pickingInfo = result;
  28527. if (fastCheck) {
  28528. break;
  28529. }
  28530. }
  28531. return pickingInfo || new BABYLON.PickingInfo();
  28532. };
  28533. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28534. if (!BABYLON.PickingInfo) {
  28535. return null;
  28536. }
  28537. var pickingInfos = new Array();
  28538. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28539. var mesh = this.meshes[meshIndex];
  28540. if (predicate) {
  28541. if (!predicate(mesh)) {
  28542. continue;
  28543. }
  28544. }
  28545. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28546. continue;
  28547. }
  28548. var world = mesh.getWorldMatrix();
  28549. var ray = rayFunction(world);
  28550. var result = mesh.intersects(ray, false);
  28551. if (!result || !result.hit)
  28552. continue;
  28553. pickingInfos.push(result);
  28554. }
  28555. return pickingInfos;
  28556. };
  28557. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28558. if (!BABYLON.PickingInfo) {
  28559. return null;
  28560. }
  28561. var pickingInfo = null;
  28562. if (!camera) {
  28563. if (!this.activeCamera) {
  28564. return null;
  28565. }
  28566. camera = this.activeCamera;
  28567. }
  28568. if (this.spriteManagers.length > 0) {
  28569. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28570. var spriteManager = this.spriteManagers[spriteIndex];
  28571. if (!spriteManager.isPickable) {
  28572. continue;
  28573. }
  28574. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28575. if (!result || !result.hit)
  28576. continue;
  28577. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28578. continue;
  28579. pickingInfo = result;
  28580. if (fastCheck) {
  28581. break;
  28582. }
  28583. }
  28584. }
  28585. return pickingInfo || new BABYLON.PickingInfo();
  28586. };
  28587. /** Launch a ray to try to pick a mesh in the scene
  28588. * @param x position on screen
  28589. * @param y position on screen
  28590. * @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
  28591. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28592. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28593. * @returns a PickingInfo
  28594. */
  28595. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28596. var _this = this;
  28597. if (!BABYLON.PickingInfo) {
  28598. return null;
  28599. }
  28600. var result = this._internalPick(function (world) {
  28601. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28602. return _this._tempPickingRay;
  28603. }, predicate, fastCheck);
  28604. if (result) {
  28605. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28606. }
  28607. return result;
  28608. };
  28609. /** Launch a ray to try to pick a sprite in the scene
  28610. * @param x position on screen
  28611. * @param y position on screen
  28612. * @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
  28613. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28614. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28615. * @returns a PickingInfo
  28616. */
  28617. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28618. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28619. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28620. };
  28621. /** Use the given ray to pick a mesh in the scene
  28622. * @param ray The ray to use to pick meshes
  28623. * @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
  28624. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28625. * @returns a PickingInfo
  28626. */
  28627. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28628. var _this = this;
  28629. var result = this._internalPick(function (world) {
  28630. if (!_this._pickWithRayInverseMatrix) {
  28631. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28632. }
  28633. world.invertToRef(_this._pickWithRayInverseMatrix);
  28634. if (!_this._cachedRayForTransform) {
  28635. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28636. }
  28637. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28638. return _this._cachedRayForTransform;
  28639. }, predicate, fastCheck);
  28640. if (result) {
  28641. result.ray = ray;
  28642. }
  28643. return result;
  28644. };
  28645. /**
  28646. * Launch a ray to try to pick a mesh in the scene
  28647. * @param x X position on screen
  28648. * @param y Y position on screen
  28649. * @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
  28650. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28651. * @returns an array of PickingInfo
  28652. */
  28653. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28654. var _this = this;
  28655. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28656. };
  28657. /**
  28658. * Launch a ray to try to pick a mesh in the scene
  28659. * @param ray Ray to use
  28660. * @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
  28661. * @returns an array of PickingInfo
  28662. */
  28663. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28664. var _this = this;
  28665. return this._internalMultiPick(function (world) {
  28666. if (!_this._pickWithRayInverseMatrix) {
  28667. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28668. }
  28669. world.invertToRef(_this._pickWithRayInverseMatrix);
  28670. if (!_this._cachedRayForTransform) {
  28671. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28672. }
  28673. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28674. return _this._cachedRayForTransform;
  28675. }, predicate);
  28676. };
  28677. /**
  28678. * Force the value of meshUnderPointer
  28679. * @param mesh defines the mesh to use
  28680. */
  28681. Scene.prototype.setPointerOverMesh = function (mesh) {
  28682. if (this._pointerOverMesh === mesh) {
  28683. return;
  28684. }
  28685. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28686. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28687. }
  28688. this._pointerOverMesh = mesh;
  28689. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28690. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28691. }
  28692. };
  28693. /**
  28694. * Gets the mesh under the pointer
  28695. * @returns a Mesh or null if no mesh is under the pointer
  28696. */
  28697. Scene.prototype.getPointerOverMesh = function () {
  28698. return this._pointerOverMesh;
  28699. };
  28700. /**
  28701. * Force the sprite under the pointer
  28702. * @param sprite defines the sprite to use
  28703. */
  28704. Scene.prototype.setPointerOverSprite = function (sprite) {
  28705. if (this._pointerOverSprite === sprite) {
  28706. return;
  28707. }
  28708. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28709. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28710. }
  28711. this._pointerOverSprite = sprite;
  28712. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28713. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28714. }
  28715. };
  28716. /**
  28717. * Gets the sprite under the pointer
  28718. * @returns a Sprite or null if no sprite is under the pointer
  28719. */
  28720. Scene.prototype.getPointerOverSprite = function () {
  28721. return this._pointerOverSprite;
  28722. };
  28723. // Physics
  28724. /**
  28725. * Gets the current physics engine
  28726. * @returns a PhysicsEngine or null if none attached
  28727. */
  28728. Scene.prototype.getPhysicsEngine = function () {
  28729. return this._physicsEngine;
  28730. };
  28731. /**
  28732. * Enables physics to the current scene
  28733. * @param gravity defines the scene's gravity for the physics engine
  28734. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28735. * @return a boolean indicating if the physics engine was initialized
  28736. */
  28737. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28738. if (gravity === void 0) { gravity = null; }
  28739. if (this._physicsEngine) {
  28740. return true;
  28741. }
  28742. try {
  28743. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28744. return true;
  28745. }
  28746. catch (e) {
  28747. BABYLON.Tools.Error(e.message);
  28748. return false;
  28749. }
  28750. };
  28751. /**
  28752. * Disables and disposes the physics engine associated with the scene
  28753. */
  28754. Scene.prototype.disablePhysicsEngine = function () {
  28755. if (!this._physicsEngine) {
  28756. return;
  28757. }
  28758. this._physicsEngine.dispose();
  28759. this._physicsEngine = null;
  28760. };
  28761. /**
  28762. * Gets a boolean indicating if there is an active physics engine
  28763. * @returns a boolean indicating if there is an active physics engine
  28764. */
  28765. Scene.prototype.isPhysicsEnabled = function () {
  28766. return this._physicsEngine !== undefined;
  28767. };
  28768. /**
  28769. * Deletes a physics compound impostor
  28770. * @param compound defines the compound to delete
  28771. */
  28772. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28773. var mesh = compound.parts[0].mesh;
  28774. if (mesh.physicsImpostor) {
  28775. mesh.physicsImpostor.dispose( /*true*/);
  28776. mesh.physicsImpostor = null;
  28777. }
  28778. };
  28779. // Misc.
  28780. /** @hidden */
  28781. Scene.prototype._rebuildGeometries = function () {
  28782. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28783. var geometry = _a[_i];
  28784. geometry._rebuild();
  28785. }
  28786. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28787. var mesh = _c[_b];
  28788. mesh._rebuild();
  28789. }
  28790. if (this.postProcessManager) {
  28791. this.postProcessManager._rebuild();
  28792. }
  28793. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28794. var layer = _e[_d];
  28795. layer._rebuild();
  28796. }
  28797. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28798. var effectLayer = _g[_f];
  28799. effectLayer._rebuild();
  28800. }
  28801. if (this._boundingBoxRenderer) {
  28802. this._boundingBoxRenderer._rebuild();
  28803. }
  28804. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28805. var system = _j[_h];
  28806. system.rebuild();
  28807. }
  28808. if (this._postProcessRenderPipelineManager) {
  28809. this._postProcessRenderPipelineManager._rebuild();
  28810. }
  28811. };
  28812. /** @hidden */
  28813. Scene.prototype._rebuildTextures = function () {
  28814. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28815. var texture = _a[_i];
  28816. texture._rebuild();
  28817. }
  28818. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28819. };
  28820. /**
  28821. * Creates a default light for the scene.
  28822. * @param replace Whether to replace the existing lights in the scene.
  28823. */
  28824. Scene.prototype.createDefaultLight = function (replace) {
  28825. if (replace === void 0) { replace = false; }
  28826. // Dispose existing light in replace mode.
  28827. if (replace) {
  28828. if (this.lights) {
  28829. for (var i = 0; i < this.lights.length; i++) {
  28830. this.lights[i].dispose();
  28831. }
  28832. }
  28833. }
  28834. // Light
  28835. if (this.lights.length === 0) {
  28836. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28837. }
  28838. };
  28839. /**
  28840. * Creates a default camera for the scene.
  28841. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28842. * @param replace Whether to replace the existing active camera in the scene.
  28843. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28844. */
  28845. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28846. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28847. if (replace === void 0) { replace = false; }
  28848. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28849. // Dispose existing camera in replace mode.
  28850. if (replace) {
  28851. if (this.activeCamera) {
  28852. this.activeCamera.dispose();
  28853. this.activeCamera = null;
  28854. }
  28855. }
  28856. // Camera
  28857. if (!this.activeCamera) {
  28858. var worldExtends = this.getWorldExtends();
  28859. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28860. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28861. var camera;
  28862. var radius = worldSize.length() * 1.5;
  28863. // empty scene scenario!
  28864. if (!isFinite(radius)) {
  28865. radius = 1;
  28866. worldCenter.copyFromFloats(0, 0, 0);
  28867. }
  28868. if (createArcRotateCamera) {
  28869. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28870. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28871. arcRotateCamera.wheelPrecision = 100 / radius;
  28872. camera = arcRotateCamera;
  28873. }
  28874. else {
  28875. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28876. freeCamera.setTarget(worldCenter);
  28877. camera = freeCamera;
  28878. }
  28879. camera.minZ = radius * 0.01;
  28880. camera.maxZ = radius * 1000;
  28881. camera.speed = radius * 0.2;
  28882. this.activeCamera = camera;
  28883. var canvas = this.getEngine().getRenderingCanvas();
  28884. if (attachCameraControls && canvas) {
  28885. camera.attachControl(canvas);
  28886. }
  28887. }
  28888. };
  28889. /**
  28890. * Creates a default camera and a default light
  28891. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28892. * @param replace defines if the camera and/or light will replace the existing ones
  28893. * @param attachCameraControls defines if attachControl will be called on the new camera
  28894. */
  28895. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28896. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28897. if (replace === void 0) { replace = false; }
  28898. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28899. this.createDefaultLight(replace);
  28900. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28901. };
  28902. /**
  28903. * Creates a new sky box
  28904. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28905. * @param environmentTexture defines the texture to use as environment texture
  28906. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28907. * @param scale defines the overall scale of the skybox
  28908. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28909. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28910. * @returns a new mesh holding the sky box
  28911. */
  28912. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28913. if (pbr === void 0) { pbr = false; }
  28914. if (scale === void 0) { scale = 1000; }
  28915. if (blur === void 0) { blur = 0; }
  28916. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28917. if (!environmentTexture) {
  28918. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28919. return null;
  28920. }
  28921. if (setGlobalEnvTexture) {
  28922. if (environmentTexture) {
  28923. this.environmentTexture = environmentTexture;
  28924. }
  28925. }
  28926. // Skybox
  28927. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28928. if (pbr) {
  28929. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28930. hdrSkyboxMaterial.backFaceCulling = false;
  28931. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28932. if (hdrSkyboxMaterial.reflectionTexture) {
  28933. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28934. }
  28935. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28936. hdrSkyboxMaterial.disableLighting = true;
  28937. hdrSkyboxMaterial.twoSidedLighting = true;
  28938. hdrSkybox.infiniteDistance = true;
  28939. hdrSkybox.material = hdrSkyboxMaterial;
  28940. }
  28941. else {
  28942. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28943. skyboxMaterial.backFaceCulling = false;
  28944. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28945. if (skyboxMaterial.reflectionTexture) {
  28946. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28947. }
  28948. skyboxMaterial.disableLighting = true;
  28949. hdrSkybox.infiniteDistance = true;
  28950. hdrSkybox.material = skyboxMaterial;
  28951. }
  28952. return hdrSkybox;
  28953. };
  28954. /**
  28955. * Creates a new environment
  28956. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28957. * @param options defines the options you can use to configure the environment
  28958. * @returns the new EnvironmentHelper
  28959. */
  28960. Scene.prototype.createDefaultEnvironment = function (options) {
  28961. if (BABYLON.EnvironmentHelper) {
  28962. return new BABYLON.EnvironmentHelper(options, this);
  28963. }
  28964. return null;
  28965. };
  28966. /**
  28967. * Creates a new VREXperienceHelper
  28968. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28969. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28970. * @returns a new VREXperienceHelper
  28971. */
  28972. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28973. if (webVROptions === void 0) { webVROptions = {}; }
  28974. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28975. };
  28976. // Tags
  28977. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28978. if (tagsQuery === undefined) {
  28979. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28980. return list;
  28981. }
  28982. var listByTags = [];
  28983. forEach = forEach || (function (item) { return; });
  28984. for (var i in list) {
  28985. var item = list[i];
  28986. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28987. listByTags.push(item);
  28988. forEach(item);
  28989. }
  28990. }
  28991. return listByTags;
  28992. };
  28993. /**
  28994. * Get a list of meshes by tags
  28995. * @param tagsQuery defines the tags query to use
  28996. * @param forEach defines a predicate used to filter results
  28997. * @returns an array of Mesh
  28998. */
  28999. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29000. return this._getByTags(this.meshes, tagsQuery, forEach);
  29001. };
  29002. /**
  29003. * Get a list of cameras by tags
  29004. * @param tagsQuery defines the tags query to use
  29005. * @param forEach defines a predicate used to filter results
  29006. * @returns an array of Camera
  29007. */
  29008. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29009. return this._getByTags(this.cameras, tagsQuery, forEach);
  29010. };
  29011. /**
  29012. * Get a list of lights by tags
  29013. * @param tagsQuery defines the tags query to use
  29014. * @param forEach defines a predicate used to filter results
  29015. * @returns an array of Light
  29016. */
  29017. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29018. return this._getByTags(this.lights, tagsQuery, forEach);
  29019. };
  29020. /**
  29021. * Get a list of materials by tags
  29022. * @param tagsQuery defines the tags query to use
  29023. * @param forEach defines a predicate used to filter results
  29024. * @returns an array of Material
  29025. */
  29026. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29027. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29028. };
  29029. /**
  29030. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29031. * This allowed control for front to back rendering or reversly depending of the special needs.
  29032. *
  29033. * @param renderingGroupId The rendering group id corresponding to its index
  29034. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29035. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29036. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29037. */
  29038. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29039. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29040. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29041. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29042. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29043. };
  29044. /**
  29045. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29046. *
  29047. * @param renderingGroupId The rendering group id corresponding to its index
  29048. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29049. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29050. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29051. */
  29052. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29053. if (depth === void 0) { depth = true; }
  29054. if (stencil === void 0) { stencil = true; }
  29055. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29056. };
  29057. /**
  29058. * Will flag all materials as dirty to trigger new shader compilation
  29059. * @param flag defines the flag used to specify which material part must be marked as dirty
  29060. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29061. */
  29062. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29063. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29064. var material = _a[_i];
  29065. if (predicate && !predicate(material)) {
  29066. continue;
  29067. }
  29068. material.markAsDirty(flag);
  29069. }
  29070. };
  29071. /** @hidden */
  29072. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29073. var _this = this;
  29074. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29075. this._activeRequests.push(request);
  29076. request.onCompleteObservable.add(function (request) {
  29077. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29078. });
  29079. return request;
  29080. };
  29081. /** @hidden */
  29082. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29083. var _this = this;
  29084. return new Promise(function (resolve, reject) {
  29085. _this._loadFile(url, function (data) {
  29086. resolve(data);
  29087. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29088. reject(exception);
  29089. });
  29090. });
  29091. };
  29092. // Statics
  29093. Scene._FOGMODE_NONE = 0;
  29094. Scene._FOGMODE_EXP = 1;
  29095. Scene._FOGMODE_EXP2 = 2;
  29096. Scene._FOGMODE_LINEAR = 3;
  29097. Scene._uniqueIdCounter = 0;
  29098. /**
  29099. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29100. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29101. */
  29102. Scene.MinDeltaTime = 1.0;
  29103. /**
  29104. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29105. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29106. */
  29107. Scene.MaxDeltaTime = 1000.0;
  29108. /** The distance in pixel that you have to move to prevent some events */
  29109. Scene.DragMovementThreshold = 10; // in pixels
  29110. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29111. Scene.LongPressDelay = 500; // in milliseconds
  29112. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29113. Scene.DoubleClickDelay = 300; // in milliseconds
  29114. /** If you need to check double click without raising a single click at first click, enable this flag */
  29115. Scene.ExclusiveDoubleClickMode = false;
  29116. return Scene;
  29117. }());
  29118. BABYLON.Scene = Scene;
  29119. })(BABYLON || (BABYLON = {}));
  29120. //# sourceMappingURL=babylon.scene.js.map
  29121. var BABYLON;
  29122. (function (BABYLON) {
  29123. /**
  29124. * Set of assets to keep when moving a scene into an asset container.
  29125. */
  29126. var KeepAssets = /** @class */ (function () {
  29127. function KeepAssets() {
  29128. /**
  29129. * Cameras to keep.
  29130. */
  29131. this.cameras = new Array();
  29132. /**
  29133. * Lights to keep.
  29134. */
  29135. this.lights = new Array();
  29136. /**
  29137. * Meshes to keep.
  29138. */
  29139. this.meshes = new Array();
  29140. /**
  29141. * Skeletons to keep.
  29142. */
  29143. this.skeletons = new Array();
  29144. /**
  29145. * ParticleSystems to keep.
  29146. */
  29147. this.particleSystems = new Array();
  29148. /**
  29149. * Animations to keep.
  29150. */
  29151. this.animations = new Array();
  29152. /**
  29153. * AnimationGroups to keep.
  29154. */
  29155. this.animationGroups = new Array();
  29156. /**
  29157. * MultiMaterials to keep.
  29158. */
  29159. this.multiMaterials = new Array();
  29160. /**
  29161. * Materials to keep.
  29162. */
  29163. this.materials = new Array();
  29164. /**
  29165. * MorphTargetManagers to keep.
  29166. */
  29167. this.morphTargetManagers = new Array();
  29168. /**
  29169. * Geometries to keep.
  29170. */
  29171. this.geometries = new Array();
  29172. /**
  29173. * TransformNodes to keep.
  29174. */
  29175. this.transformNodes = new Array();
  29176. /**
  29177. * LensFlareSystems to keep.
  29178. */
  29179. this.lensFlareSystems = new Array();
  29180. /**
  29181. * ShadowGenerators to keep.
  29182. */
  29183. this.shadowGenerators = new Array();
  29184. /**
  29185. * ActionManagers to keep.
  29186. */
  29187. this.actionManagers = new Array();
  29188. /**
  29189. * Sounds to keep.
  29190. */
  29191. this.sounds = new Array();
  29192. /**
  29193. * Textures to keep.
  29194. */
  29195. this.textures = new Array();
  29196. /**
  29197. * Effect layers to keep.
  29198. */
  29199. this.effectLayers = new Array();
  29200. }
  29201. return KeepAssets;
  29202. }());
  29203. BABYLON.KeepAssets = KeepAssets;
  29204. /**
  29205. * Container with a set of assets that can be added or removed from a scene.
  29206. */
  29207. var AssetContainer = /** @class */ (function () {
  29208. /**
  29209. * Instantiates an AssetContainer.
  29210. * @param scene The scene the AssetContainer belongs to.
  29211. */
  29212. function AssetContainer(scene) {
  29213. // Objects
  29214. /**
  29215. * Cameras populated in the container.
  29216. */
  29217. this.cameras = new Array();
  29218. /**
  29219. * Lights populated in the container.
  29220. */
  29221. this.lights = new Array();
  29222. /**
  29223. * Meshes populated in the container.
  29224. */
  29225. this.meshes = new Array();
  29226. /**
  29227. * Skeletons populated in the container.
  29228. */
  29229. this.skeletons = new Array();
  29230. /**
  29231. * ParticleSystems populated in the container.
  29232. */
  29233. this.particleSystems = new Array();
  29234. /**
  29235. * Animations populated in the container.
  29236. */
  29237. this.animations = new Array();
  29238. /**
  29239. * AnimationGroups populated in the container.
  29240. */
  29241. this.animationGroups = new Array();
  29242. /**
  29243. * MultiMaterials populated in the container.
  29244. */
  29245. this.multiMaterials = new Array();
  29246. /**
  29247. * Materials populated in the container.
  29248. */
  29249. this.materials = new Array();
  29250. /**
  29251. * MorphTargetManagers populated in the container.
  29252. */
  29253. this.morphTargetManagers = new Array();
  29254. /**
  29255. * Geometries populated in the container.
  29256. */
  29257. this.geometries = new Array();
  29258. /**
  29259. * TransformNodes populated in the container.
  29260. */
  29261. this.transformNodes = new Array();
  29262. /**
  29263. * LensFlareSystems populated in the container.
  29264. */
  29265. this.lensFlareSystems = new Array();
  29266. /**
  29267. * ShadowGenerators populated in the container.
  29268. */
  29269. this.shadowGenerators = new Array();
  29270. /**
  29271. * ActionManagers populated in the container.
  29272. */
  29273. this.actionManagers = new Array();
  29274. /**
  29275. * Sounds populated in the container.
  29276. */
  29277. this.sounds = new Array();
  29278. /**
  29279. * Textures populated in the container.
  29280. */
  29281. this.textures = new Array();
  29282. /**
  29283. * Effect layers populated in the container.
  29284. */
  29285. this.effectLayers = new Array();
  29286. this.scene = scene;
  29287. }
  29288. /**
  29289. * Adds all the assets from the container to the scene.
  29290. */
  29291. AssetContainer.prototype.addAllToScene = function () {
  29292. var _this = this;
  29293. this.cameras.forEach(function (o) {
  29294. _this.scene.addCamera(o);
  29295. });
  29296. this.lights.forEach(function (o) {
  29297. _this.scene.addLight(o);
  29298. });
  29299. this.meshes.forEach(function (o) {
  29300. _this.scene.addMesh(o);
  29301. });
  29302. this.skeletons.forEach(function (o) {
  29303. _this.scene.addSkeleton(o);
  29304. });
  29305. this.particleSystems.forEach(function (o) {
  29306. _this.scene.addParticleSystem(o);
  29307. });
  29308. this.animations.forEach(function (o) {
  29309. _this.scene.addAnimation(o);
  29310. });
  29311. this.animationGroups.forEach(function (o) {
  29312. _this.scene.addAnimationGroup(o);
  29313. });
  29314. this.multiMaterials.forEach(function (o) {
  29315. _this.scene.addMultiMaterial(o);
  29316. });
  29317. this.materials.forEach(function (o) {
  29318. _this.scene.addMaterial(o);
  29319. });
  29320. this.morphTargetManagers.forEach(function (o) {
  29321. _this.scene.addMorphTargetManager(o);
  29322. });
  29323. this.geometries.forEach(function (o) {
  29324. _this.scene.addGeometry(o);
  29325. });
  29326. this.transformNodes.forEach(function (o) {
  29327. _this.scene.addTransformNode(o);
  29328. });
  29329. this.lensFlareSystems.forEach(function (o) {
  29330. _this.scene.addLensFlareSystem(o);
  29331. });
  29332. this.actionManagers.forEach(function (o) {
  29333. _this.scene.addActionManager(o);
  29334. });
  29335. this.sounds.forEach(function (o) {
  29336. o.play();
  29337. o.autoplay = true;
  29338. _this.scene.mainSoundTrack.AddSound(o);
  29339. });
  29340. this.textures.forEach(function (o) {
  29341. _this.scene.addTexture(o);
  29342. });
  29343. this.effectLayers.forEach(function (o) {
  29344. _this.scene.addEffectLayer(o);
  29345. });
  29346. };
  29347. /**
  29348. * Removes all the assets in the container from the scene
  29349. */
  29350. AssetContainer.prototype.removeAllFromScene = function () {
  29351. var _this = this;
  29352. this.cameras.forEach(function (o) {
  29353. _this.scene.removeCamera(o);
  29354. });
  29355. this.lights.forEach(function (o) {
  29356. _this.scene.removeLight(o);
  29357. });
  29358. this.meshes.forEach(function (o) {
  29359. _this.scene.removeMesh(o);
  29360. });
  29361. this.skeletons.forEach(function (o) {
  29362. _this.scene.removeSkeleton(o);
  29363. });
  29364. this.particleSystems.forEach(function (o) {
  29365. _this.scene.removeParticleSystem(o);
  29366. });
  29367. this.animations.forEach(function (o) {
  29368. _this.scene.removeAnimation(o);
  29369. });
  29370. this.animationGroups.forEach(function (o) {
  29371. _this.scene.removeAnimationGroup(o);
  29372. });
  29373. this.multiMaterials.forEach(function (o) {
  29374. _this.scene.removeMultiMaterial(o);
  29375. });
  29376. this.materials.forEach(function (o) {
  29377. _this.scene.removeMaterial(o);
  29378. });
  29379. this.morphTargetManagers.forEach(function (o) {
  29380. _this.scene.removeMorphTargetManager(o);
  29381. });
  29382. this.geometries.forEach(function (o) {
  29383. _this.scene.removeGeometry(o);
  29384. });
  29385. this.transformNodes.forEach(function (o) {
  29386. _this.scene.removeTransformNode(o);
  29387. });
  29388. this.lensFlareSystems.forEach(function (o) {
  29389. _this.scene.removeLensFlareSystem(o);
  29390. });
  29391. this.actionManagers.forEach(function (o) {
  29392. _this.scene.removeActionManager(o);
  29393. });
  29394. this.sounds.forEach(function (o) {
  29395. o.stop();
  29396. o.autoplay = false;
  29397. _this.scene.mainSoundTrack.RemoveSound(o);
  29398. });
  29399. this.textures.forEach(function (o) {
  29400. _this.scene.removeTexture(o);
  29401. });
  29402. this.effectLayers.forEach(function (o) {
  29403. _this.scene.removeEffectLayer(o);
  29404. });
  29405. };
  29406. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29407. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29408. var asset = sourceAssets_1[_i];
  29409. var move = true;
  29410. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29411. var keepAsset = keepAssets_1[_a];
  29412. if (asset === keepAsset) {
  29413. move = false;
  29414. break;
  29415. }
  29416. }
  29417. if (move) {
  29418. targetAssets.push(asset);
  29419. }
  29420. }
  29421. };
  29422. /**
  29423. * Removes all the assets contained in the scene and adds them to the container.
  29424. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29425. */
  29426. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29427. if (keepAssets === undefined) {
  29428. keepAssets = new KeepAssets();
  29429. }
  29430. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29431. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29432. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29433. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29434. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29435. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29436. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29437. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29438. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29439. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29440. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29441. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29442. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29443. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29444. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29445. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29446. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29447. this.removeAllFromScene();
  29448. };
  29449. /**
  29450. * 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.
  29451. * @returns the root mesh
  29452. */
  29453. AssetContainer.prototype.createRootMesh = function () {
  29454. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29455. this.meshes.forEach(function (m) {
  29456. if (!m.parent) {
  29457. rootMesh.addChild(m);
  29458. }
  29459. });
  29460. this.meshes.unshift(rootMesh);
  29461. return rootMesh;
  29462. };
  29463. return AssetContainer;
  29464. }());
  29465. BABYLON.AssetContainer = AssetContainer;
  29466. })(BABYLON || (BABYLON = {}));
  29467. //# sourceMappingURL=babylon.assetContainer.js.map
  29468. var BABYLON;
  29469. (function (BABYLON) {
  29470. var Buffer = /** @class */ (function () {
  29471. /**
  29472. * Constructor
  29473. * @param engine the engine
  29474. * @param data the data to use for this buffer
  29475. * @param updatable whether the data is updatable
  29476. * @param stride the stride (optional)
  29477. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29478. * @param instanced whether the buffer is instanced (optional)
  29479. * @param useBytes set to true if the stride in in bytes (optional)
  29480. */
  29481. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29482. if (stride === void 0) { stride = 0; }
  29483. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29484. if (instanced === void 0) { instanced = false; }
  29485. if (useBytes === void 0) { useBytes = false; }
  29486. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29487. this._engine = engine.getScene().getEngine();
  29488. }
  29489. else {
  29490. this._engine = engine;
  29491. }
  29492. this._updatable = updatable;
  29493. this._instanced = instanced;
  29494. this._data = data;
  29495. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29496. if (!postponeInternalCreation) { // by default
  29497. this.create();
  29498. }
  29499. }
  29500. /**
  29501. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29502. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29503. * @param offset defines offset in the buffer (0 by default)
  29504. * @param size defines the size in floats of attributes (position is 3 for instance)
  29505. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29506. * @param instanced defines if the vertex buffer contains indexed data
  29507. * @param useBytes defines if the offset and stride are in bytes
  29508. * @returns the new vertex buffer
  29509. */
  29510. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29511. if (useBytes === void 0) { useBytes = false; }
  29512. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29513. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29514. // a lot of these parameters are ignored as they are overriden by the buffer
  29515. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29516. };
  29517. // Properties
  29518. Buffer.prototype.isUpdatable = function () {
  29519. return this._updatable;
  29520. };
  29521. Buffer.prototype.getData = function () {
  29522. return this._data;
  29523. };
  29524. Buffer.prototype.getBuffer = function () {
  29525. return this._buffer;
  29526. };
  29527. /**
  29528. * Gets the stride in float32 units (i.e. byte stride / 4).
  29529. * May not be an integer if the byte stride is not divisible by 4.
  29530. * DEPRECATED. Use byteStride instead.
  29531. * @returns the stride in float32 units
  29532. */
  29533. Buffer.prototype.getStrideSize = function () {
  29534. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29535. };
  29536. // Methods
  29537. Buffer.prototype.create = function (data) {
  29538. if (data === void 0) { data = null; }
  29539. if (!data && this._buffer) {
  29540. return; // nothing to do
  29541. }
  29542. data = data || this._data;
  29543. if (!data) {
  29544. return;
  29545. }
  29546. if (!this._buffer) { // create buffer
  29547. if (this._updatable) {
  29548. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29549. this._data = data;
  29550. }
  29551. else {
  29552. this._buffer = this._engine.createVertexBuffer(data);
  29553. }
  29554. }
  29555. else if (this._updatable) { // update buffer
  29556. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29557. this._data = data;
  29558. }
  29559. };
  29560. Buffer.prototype._rebuild = function () {
  29561. this._buffer = null;
  29562. this.create(this._data);
  29563. };
  29564. Buffer.prototype.update = function (data) {
  29565. this.create(data);
  29566. };
  29567. /**
  29568. * Updates the data directly.
  29569. * @param data the new data
  29570. * @param offset the new offset
  29571. * @param vertexCount the vertex count (optional)
  29572. * @param useBytes set to true if the offset is in bytes
  29573. */
  29574. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29575. if (useBytes === void 0) { useBytes = false; }
  29576. if (!this._buffer) {
  29577. return;
  29578. }
  29579. if (this._updatable) { // update buffer
  29580. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29581. this._data = null;
  29582. }
  29583. };
  29584. Buffer.prototype.dispose = function () {
  29585. if (!this._buffer) {
  29586. return;
  29587. }
  29588. if (this._engine._releaseBuffer(this._buffer)) {
  29589. this._buffer = null;
  29590. }
  29591. };
  29592. return Buffer;
  29593. }());
  29594. BABYLON.Buffer = Buffer;
  29595. })(BABYLON || (BABYLON = {}));
  29596. //# sourceMappingURL=babylon.buffer.js.map
  29597. var BABYLON;
  29598. (function (BABYLON) {
  29599. var VertexBuffer = /** @class */ (function () {
  29600. /**
  29601. * Constructor
  29602. * @param engine the engine
  29603. * @param data the data to use for this vertex buffer
  29604. * @param kind the vertex buffer kind
  29605. * @param updatable whether the data is updatable
  29606. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29607. * @param stride the stride (optional)
  29608. * @param instanced whether the buffer is instanced (optional)
  29609. * @param offset the offset of the data (optional)
  29610. * @param size the number of components (optional)
  29611. * @param type the type of the component (optional)
  29612. * @param normalized whether the data contains normalized data (optional)
  29613. * @param useBytes set to true if stride and offset are in bytes (optional)
  29614. */
  29615. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29616. if (normalized === void 0) { normalized = false; }
  29617. if (useBytes === void 0) { useBytes = false; }
  29618. if (data instanceof BABYLON.Buffer) {
  29619. this._buffer = data;
  29620. this._ownsBuffer = false;
  29621. }
  29622. else {
  29623. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29624. this._ownsBuffer = true;
  29625. }
  29626. this._kind = kind;
  29627. if (type == undefined) {
  29628. var data_1 = this.getData();
  29629. this.type = VertexBuffer.FLOAT;
  29630. if (data_1 instanceof Int8Array)
  29631. this.type = VertexBuffer.BYTE;
  29632. else if (data_1 instanceof Uint8Array)
  29633. this.type = VertexBuffer.UNSIGNED_BYTE;
  29634. else if (data_1 instanceof Int16Array)
  29635. this.type = VertexBuffer.SHORT;
  29636. else if (data_1 instanceof Uint16Array)
  29637. this.type = VertexBuffer.UNSIGNED_SHORT;
  29638. else if (data_1 instanceof Int32Array)
  29639. this.type = VertexBuffer.INT;
  29640. else if (data_1 instanceof Uint32Array)
  29641. this.type = VertexBuffer.UNSIGNED_INT;
  29642. }
  29643. else {
  29644. this.type = type;
  29645. }
  29646. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29647. if (useBytes) {
  29648. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29649. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29650. this.byteOffset = offset || 0;
  29651. }
  29652. else {
  29653. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29654. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29655. this.byteOffset = (offset || 0) * typeByteLength;
  29656. }
  29657. this.normalized = normalized;
  29658. this._instanced = instanced !== undefined ? instanced : false;
  29659. this._instanceDivisor = instanced ? 1 : 0;
  29660. }
  29661. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29662. /**
  29663. * Gets or sets the instance divisor when in instanced mode
  29664. */
  29665. get: function () {
  29666. return this._instanceDivisor;
  29667. },
  29668. set: function (value) {
  29669. this._instanceDivisor = value;
  29670. if (value == 0) {
  29671. this._instanced = false;
  29672. }
  29673. else {
  29674. this._instanced = true;
  29675. }
  29676. },
  29677. enumerable: true,
  29678. configurable: true
  29679. });
  29680. VertexBuffer.prototype._rebuild = function () {
  29681. if (!this._buffer) {
  29682. return;
  29683. }
  29684. this._buffer._rebuild();
  29685. };
  29686. /**
  29687. * Returns the kind of the VertexBuffer (string).
  29688. */
  29689. VertexBuffer.prototype.getKind = function () {
  29690. return this._kind;
  29691. };
  29692. // Properties
  29693. /**
  29694. * Boolean : is the VertexBuffer updatable ?
  29695. */
  29696. VertexBuffer.prototype.isUpdatable = function () {
  29697. return this._buffer.isUpdatable();
  29698. };
  29699. /**
  29700. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29701. */
  29702. VertexBuffer.prototype.getData = function () {
  29703. return this._buffer.getData();
  29704. };
  29705. /**
  29706. * Returns the WebGLBuffer associated to the VertexBuffer.
  29707. */
  29708. VertexBuffer.prototype.getBuffer = function () {
  29709. return this._buffer.getBuffer();
  29710. };
  29711. /**
  29712. * Returns the stride as a multiple of the type byte length.
  29713. * DEPRECATED. Use byteStride instead.
  29714. */
  29715. VertexBuffer.prototype.getStrideSize = function () {
  29716. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29717. };
  29718. /**
  29719. * Returns the offset as a multiple of the type byte length.
  29720. * DEPRECATED. Use byteOffset instead.
  29721. */
  29722. VertexBuffer.prototype.getOffset = function () {
  29723. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29724. };
  29725. /**
  29726. * Returns the number of components per vertex attribute (integer).
  29727. */
  29728. VertexBuffer.prototype.getSize = function () {
  29729. return this._size;
  29730. };
  29731. /**
  29732. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29733. */
  29734. VertexBuffer.prototype.getIsInstanced = function () {
  29735. return this._instanced;
  29736. };
  29737. /**
  29738. * Returns the instancing divisor, zero for non-instanced (integer).
  29739. */
  29740. VertexBuffer.prototype.getInstanceDivisor = function () {
  29741. return this._instanceDivisor;
  29742. };
  29743. // Methods
  29744. /**
  29745. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29746. * Returns the created WebGLBuffer.
  29747. */
  29748. VertexBuffer.prototype.create = function (data) {
  29749. return this._buffer.create(data);
  29750. };
  29751. /**
  29752. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29753. * This function will create a new buffer if the current one is not updatable
  29754. * Returns the updated WebGLBuffer.
  29755. */
  29756. VertexBuffer.prototype.update = function (data) {
  29757. return this._buffer.update(data);
  29758. };
  29759. /**
  29760. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29761. * Returns the directly updated WebGLBuffer.
  29762. * @param data the new data
  29763. * @param offset the new offset
  29764. * @param useBytes set to true if the offset is in bytes
  29765. */
  29766. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29767. if (useBytes === void 0) { useBytes = false; }
  29768. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29769. };
  29770. /**
  29771. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29772. */
  29773. VertexBuffer.prototype.dispose = function () {
  29774. if (this._ownsBuffer) {
  29775. this._buffer.dispose();
  29776. }
  29777. };
  29778. /**
  29779. * Enumerates each value of this vertex buffer as numbers.
  29780. * @param count the number of values to enumerate
  29781. * @param callback the callback function called for each value
  29782. */
  29783. VertexBuffer.prototype.forEach = function (count, callback) {
  29784. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29785. };
  29786. Object.defineProperty(VertexBuffer, "PositionKind", {
  29787. get: function () {
  29788. return VertexBuffer._PositionKind;
  29789. },
  29790. enumerable: true,
  29791. configurable: true
  29792. });
  29793. Object.defineProperty(VertexBuffer, "NormalKind", {
  29794. get: function () {
  29795. return VertexBuffer._NormalKind;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. Object.defineProperty(VertexBuffer, "TangentKind", {
  29801. get: function () {
  29802. return VertexBuffer._TangentKind;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. Object.defineProperty(VertexBuffer, "UVKind", {
  29808. get: function () {
  29809. return VertexBuffer._UVKind;
  29810. },
  29811. enumerable: true,
  29812. configurable: true
  29813. });
  29814. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29815. get: function () {
  29816. return VertexBuffer._UV2Kind;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29822. get: function () {
  29823. return VertexBuffer._UV3Kind;
  29824. },
  29825. enumerable: true,
  29826. configurable: true
  29827. });
  29828. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29829. get: function () {
  29830. return VertexBuffer._UV4Kind;
  29831. },
  29832. enumerable: true,
  29833. configurable: true
  29834. });
  29835. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29836. get: function () {
  29837. return VertexBuffer._UV5Kind;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29843. get: function () {
  29844. return VertexBuffer._UV6Kind;
  29845. },
  29846. enumerable: true,
  29847. configurable: true
  29848. });
  29849. Object.defineProperty(VertexBuffer, "ColorKind", {
  29850. get: function () {
  29851. return VertexBuffer._ColorKind;
  29852. },
  29853. enumerable: true,
  29854. configurable: true
  29855. });
  29856. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29857. get: function () {
  29858. return VertexBuffer._MatricesIndicesKind;
  29859. },
  29860. enumerable: true,
  29861. configurable: true
  29862. });
  29863. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29864. get: function () {
  29865. return VertexBuffer._MatricesWeightsKind;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29871. get: function () {
  29872. return VertexBuffer._MatricesIndicesExtraKind;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29878. get: function () {
  29879. return VertexBuffer._MatricesWeightsExtraKind;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. /**
  29885. * Deduces the stride given a kind.
  29886. * @param kind The kind string to deduce
  29887. * @returns The deduced stride
  29888. */
  29889. VertexBuffer.DeduceStride = function (kind) {
  29890. switch (kind) {
  29891. case VertexBuffer.UVKind:
  29892. case VertexBuffer.UV2Kind:
  29893. case VertexBuffer.UV3Kind:
  29894. case VertexBuffer.UV4Kind:
  29895. case VertexBuffer.UV5Kind:
  29896. case VertexBuffer.UV6Kind:
  29897. return 2;
  29898. case VertexBuffer.NormalKind:
  29899. case VertexBuffer.PositionKind:
  29900. return 3;
  29901. case VertexBuffer.ColorKind:
  29902. case VertexBuffer.MatricesIndicesKind:
  29903. case VertexBuffer.MatricesIndicesExtraKind:
  29904. case VertexBuffer.MatricesWeightsKind:
  29905. case VertexBuffer.MatricesWeightsExtraKind:
  29906. case VertexBuffer.TangentKind:
  29907. return 4;
  29908. default:
  29909. throw new Error("Invalid kind '" + kind + "'");
  29910. }
  29911. };
  29912. /**
  29913. * Gets the byte length of the given type.
  29914. * @param type the type
  29915. * @returns the number of bytes
  29916. */
  29917. VertexBuffer.GetTypeByteLength = function (type) {
  29918. switch (type) {
  29919. case VertexBuffer.BYTE:
  29920. case VertexBuffer.UNSIGNED_BYTE:
  29921. return 1;
  29922. case VertexBuffer.SHORT:
  29923. case VertexBuffer.UNSIGNED_SHORT:
  29924. return 2;
  29925. case VertexBuffer.INT:
  29926. case VertexBuffer.FLOAT:
  29927. return 4;
  29928. default:
  29929. throw new Error("Invalid type '" + type + "'");
  29930. }
  29931. };
  29932. /**
  29933. * Enumerates each value of the given parameters as numbers.
  29934. * @param data the data to enumerate
  29935. * @param byteOffset the byte offset of the data
  29936. * @param byteStride the byte stride of the data
  29937. * @param componentCount the number of components per element
  29938. * @param componentType the type of the component
  29939. * @param count the total number of components
  29940. * @param normalized whether the data is normalized
  29941. * @param callback the callback function called for each value
  29942. */
  29943. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29944. if (data instanceof Array) {
  29945. var offset = byteOffset / 4;
  29946. var stride = byteStride / 4;
  29947. for (var index = 0; index < count; index += componentCount) {
  29948. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29949. callback(data[offset + componentIndex], index + componentIndex);
  29950. }
  29951. offset += stride;
  29952. }
  29953. }
  29954. else {
  29955. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29956. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29957. for (var index = 0; index < count; index += componentCount) {
  29958. var componentByteOffset = byteOffset;
  29959. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29960. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29961. callback(value, index + componentIndex);
  29962. componentByteOffset += componentByteLength;
  29963. }
  29964. byteOffset += byteStride;
  29965. }
  29966. }
  29967. };
  29968. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29969. switch (type) {
  29970. case VertexBuffer.BYTE: {
  29971. var value = dataView.getInt8(byteOffset);
  29972. if (normalized) {
  29973. value = Math.max(value / 127, -1);
  29974. }
  29975. return value;
  29976. }
  29977. case VertexBuffer.UNSIGNED_BYTE: {
  29978. var value = dataView.getUint8(byteOffset);
  29979. if (normalized) {
  29980. value = value / 255;
  29981. }
  29982. return value;
  29983. }
  29984. case VertexBuffer.SHORT: {
  29985. var value = dataView.getInt16(byteOffset, true);
  29986. if (normalized) {
  29987. value = Math.max(value / 16383, -1);
  29988. }
  29989. return value;
  29990. }
  29991. case VertexBuffer.UNSIGNED_SHORT: {
  29992. var value = dataView.getUint16(byteOffset, true);
  29993. if (normalized) {
  29994. value = value / 65535;
  29995. }
  29996. return value;
  29997. }
  29998. case VertexBuffer.FLOAT: {
  29999. return dataView.getFloat32(byteOffset, true);
  30000. }
  30001. default: {
  30002. throw new Error("Invalid component type " + type);
  30003. }
  30004. }
  30005. };
  30006. /**
  30007. * The byte type.
  30008. */
  30009. VertexBuffer.BYTE = 5120;
  30010. /**
  30011. * The unsigned byte type.
  30012. */
  30013. VertexBuffer.UNSIGNED_BYTE = 5121;
  30014. /**
  30015. * The short type.
  30016. */
  30017. VertexBuffer.SHORT = 5122;
  30018. /**
  30019. * The unsigned short type.
  30020. */
  30021. VertexBuffer.UNSIGNED_SHORT = 5123;
  30022. /**
  30023. * The integer type.
  30024. */
  30025. VertexBuffer.INT = 5124;
  30026. /**
  30027. * The unsigned integer type.
  30028. */
  30029. VertexBuffer.UNSIGNED_INT = 5125;
  30030. /**
  30031. * The float type.
  30032. */
  30033. VertexBuffer.FLOAT = 5126;
  30034. // Enums
  30035. VertexBuffer._PositionKind = "position";
  30036. VertexBuffer._NormalKind = "normal";
  30037. VertexBuffer._TangentKind = "tangent";
  30038. VertexBuffer._UVKind = "uv";
  30039. VertexBuffer._UV2Kind = "uv2";
  30040. VertexBuffer._UV3Kind = "uv3";
  30041. VertexBuffer._UV4Kind = "uv4";
  30042. VertexBuffer._UV5Kind = "uv5";
  30043. VertexBuffer._UV6Kind = "uv6";
  30044. VertexBuffer._ColorKind = "color";
  30045. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30046. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30047. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30048. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30049. return VertexBuffer;
  30050. }());
  30051. BABYLON.VertexBuffer = VertexBuffer;
  30052. })(BABYLON || (BABYLON = {}));
  30053. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30054. var BABYLON;
  30055. (function (BABYLON) {
  30056. /**
  30057. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30058. */
  30059. var DummyInternalTextureTracker = /** @class */ (function () {
  30060. function DummyInternalTextureTracker() {
  30061. /**
  30062. * Gets or set the previous tracker in the list
  30063. */
  30064. this.previous = null;
  30065. /**
  30066. * Gets or set the next tracker in the list
  30067. */
  30068. this.next = null;
  30069. }
  30070. return DummyInternalTextureTracker;
  30071. }());
  30072. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30073. })(BABYLON || (BABYLON = {}));
  30074. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30075. var BABYLON;
  30076. (function (BABYLON) {
  30077. /**
  30078. * Class used to store data associated with WebGL texture data for the engine
  30079. * This class should not be used directly
  30080. */
  30081. var InternalTexture = /** @class */ (function () {
  30082. /**
  30083. * Creates a new InternalTexture
  30084. * @param engine defines the engine to use
  30085. * @param dataSource defines the type of data that will be used
  30086. */
  30087. function InternalTexture(engine, dataSource) {
  30088. /**
  30089. * Observable called when the texture is loaded
  30090. */
  30091. this.onLoadedObservable = new BABYLON.Observable();
  30092. /**
  30093. * Gets or set the previous tracker in the list
  30094. */
  30095. this.previous = null;
  30096. /**
  30097. * Gets or set the next tracker in the list
  30098. */
  30099. this.next = null;
  30100. // Private
  30101. /** @hidden */
  30102. this._initialSlot = -1;
  30103. /** @hidden */
  30104. this._designatedSlot = -1;
  30105. /** @hidden */
  30106. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30107. /** @hidden */
  30108. this._comparisonFunction = 0;
  30109. /** @hidden */
  30110. this._isRGBD = false;
  30111. /** @hidden */
  30112. this._references = 1;
  30113. this._engine = engine;
  30114. this._dataSource = dataSource;
  30115. this._webGLTexture = engine._createTexture();
  30116. }
  30117. /**
  30118. * Gets the Engine the texture belongs to.
  30119. * @returns The babylon engine
  30120. */
  30121. InternalTexture.prototype.getEngine = function () {
  30122. return this._engine;
  30123. };
  30124. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30125. /**
  30126. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30127. */
  30128. get: function () {
  30129. return this._dataSource;
  30130. },
  30131. enumerable: true,
  30132. configurable: true
  30133. });
  30134. /**
  30135. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30136. */
  30137. InternalTexture.prototype.incrementReferences = function () {
  30138. this._references++;
  30139. };
  30140. /**
  30141. * Change the size of the texture (not the size of the content)
  30142. * @param width defines the new width
  30143. * @param height defines the new height
  30144. * @param depth defines the new depth (1 by default)
  30145. */
  30146. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30147. if (depth === void 0) { depth = 1; }
  30148. this.width = width;
  30149. this.height = height;
  30150. this.depth = depth;
  30151. this.baseWidth = width;
  30152. this.baseHeight = height;
  30153. this.baseDepth = depth;
  30154. this._size = width * height * depth;
  30155. };
  30156. /** @hidden */
  30157. InternalTexture.prototype._rebuild = function () {
  30158. var _this = this;
  30159. var proxy;
  30160. this.isReady = false;
  30161. this._cachedCoordinatesMode = null;
  30162. this._cachedWrapU = null;
  30163. this._cachedWrapV = null;
  30164. this._cachedAnisotropicFilteringLevel = null;
  30165. switch (this._dataSource) {
  30166. case InternalTexture.DATASOURCE_TEMP:
  30167. return;
  30168. case InternalTexture.DATASOURCE_URL:
  30169. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30170. _this.isReady = true;
  30171. }, null, this._buffer, undefined, this.format);
  30172. proxy._swapAndDie(this);
  30173. return;
  30174. case InternalTexture.DATASOURCE_RAW:
  30175. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30176. proxy._swapAndDie(this);
  30177. this.isReady = true;
  30178. return;
  30179. case InternalTexture.DATASOURCE_RAW3D:
  30180. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30181. proxy._swapAndDie(this);
  30182. this.isReady = true;
  30183. return;
  30184. case InternalTexture.DATASOURCE_DYNAMIC:
  30185. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30186. proxy._swapAndDie(this);
  30187. // The engine will make sure to update content so no need to flag it as isReady = true
  30188. return;
  30189. case InternalTexture.DATASOURCE_RENDERTARGET:
  30190. var options = new BABYLON.RenderTargetCreationOptions();
  30191. options.generateDepthBuffer = this._generateDepthBuffer;
  30192. options.generateMipMaps = this.generateMipMaps;
  30193. options.generateStencilBuffer = this._generateStencilBuffer;
  30194. options.samplingMode = this.samplingMode;
  30195. options.type = this.type;
  30196. if (this.isCube) {
  30197. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30198. }
  30199. else {
  30200. var size = {
  30201. width: this.width,
  30202. height: this.height
  30203. };
  30204. proxy = this._engine.createRenderTargetTexture(size, options);
  30205. }
  30206. proxy._swapAndDie(this);
  30207. this.isReady = true;
  30208. return;
  30209. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30210. var depthTextureOptions = {
  30211. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30212. comparisonFunction: this._comparisonFunction,
  30213. generateStencil: this._generateStencilBuffer,
  30214. isCube: this.isCube
  30215. };
  30216. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30217. proxy._swapAndDie(this);
  30218. this.isReady = true;
  30219. return;
  30220. case InternalTexture.DATASOURCE_CUBE:
  30221. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30222. _this.isReady = true;
  30223. }, null, this.format, this._extension);
  30224. proxy._swapAndDie(this);
  30225. return;
  30226. case InternalTexture.DATASOURCE_CUBERAW:
  30227. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30228. proxy._swapAndDie(this);
  30229. this.isReady = true;
  30230. return;
  30231. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30232. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30233. if (proxy) {
  30234. proxy._swapAndDie(_this);
  30235. }
  30236. _this.isReady = true;
  30237. }, null, this.format, this._extension);
  30238. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30239. return;
  30240. }
  30241. };
  30242. InternalTexture.prototype._swapAndDie = function (target) {
  30243. target._webGLTexture = this._webGLTexture;
  30244. if (this._framebuffer) {
  30245. target._framebuffer = this._framebuffer;
  30246. }
  30247. if (this._depthStencilBuffer) {
  30248. target._depthStencilBuffer = this._depthStencilBuffer;
  30249. }
  30250. if (this._lodTextureHigh) {
  30251. if (target._lodTextureHigh) {
  30252. target._lodTextureHigh.dispose();
  30253. }
  30254. target._lodTextureHigh = this._lodTextureHigh;
  30255. }
  30256. if (this._lodTextureMid) {
  30257. if (target._lodTextureMid) {
  30258. target._lodTextureMid.dispose();
  30259. }
  30260. target._lodTextureMid = this._lodTextureMid;
  30261. }
  30262. if (this._lodTextureLow) {
  30263. if (target._lodTextureLow) {
  30264. target._lodTextureLow.dispose();
  30265. }
  30266. target._lodTextureLow = this._lodTextureLow;
  30267. }
  30268. var cache = this._engine.getLoadedTexturesCache();
  30269. var index = cache.indexOf(this);
  30270. if (index !== -1) {
  30271. cache.splice(index, 1);
  30272. }
  30273. };
  30274. /**
  30275. * Dispose the current allocated resources
  30276. */
  30277. InternalTexture.prototype.dispose = function () {
  30278. if (!this._webGLTexture) {
  30279. return;
  30280. }
  30281. this._references--;
  30282. if (this._references === 0) {
  30283. this._engine._releaseTexture(this);
  30284. this._webGLTexture = null;
  30285. this.previous = null;
  30286. this.next = null;
  30287. }
  30288. };
  30289. /**
  30290. * The source of the texture data is unknown
  30291. */
  30292. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30293. /**
  30294. * Texture data comes from an URL
  30295. */
  30296. InternalTexture.DATASOURCE_URL = 1;
  30297. /**
  30298. * Texture data is only used for temporary storage
  30299. */
  30300. InternalTexture.DATASOURCE_TEMP = 2;
  30301. /**
  30302. * Texture data comes from raw data (ArrayBuffer)
  30303. */
  30304. InternalTexture.DATASOURCE_RAW = 3;
  30305. /**
  30306. * Texture content is dynamic (video or dynamic texture)
  30307. */
  30308. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30309. /**
  30310. * Texture content is generated by rendering to it
  30311. */
  30312. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30313. /**
  30314. * Texture content is part of a multi render target process
  30315. */
  30316. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30317. /**
  30318. * Texture data comes from a cube data file
  30319. */
  30320. InternalTexture.DATASOURCE_CUBE = 7;
  30321. /**
  30322. * Texture data comes from a raw cube data
  30323. */
  30324. InternalTexture.DATASOURCE_CUBERAW = 8;
  30325. /**
  30326. * Texture data come from a prefiltered cube data file
  30327. */
  30328. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30329. /**
  30330. * Texture content is raw 3D data
  30331. */
  30332. InternalTexture.DATASOURCE_RAW3D = 10;
  30333. /**
  30334. * Texture content is a depth texture
  30335. */
  30336. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30337. return InternalTexture;
  30338. }());
  30339. BABYLON.InternalTexture = InternalTexture;
  30340. })(BABYLON || (BABYLON = {}));
  30341. //# sourceMappingURL=babylon.internalTexture.js.map
  30342. var BABYLON;
  30343. (function (BABYLON) {
  30344. var BaseTexture = /** @class */ (function () {
  30345. function BaseTexture(scene) {
  30346. this._hasAlpha = false;
  30347. this.getAlphaFromRGB = false;
  30348. this.level = 1;
  30349. this.coordinatesIndex = 0;
  30350. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30351. /**
  30352. * | Value | Type | Description |
  30353. * | ----- | ------------------ | ----------- |
  30354. * | 0 | CLAMP_ADDRESSMODE | |
  30355. * | 1 | WRAP_ADDRESSMODE | |
  30356. * | 2 | MIRROR_ADDRESSMODE | |
  30357. */
  30358. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30359. /**
  30360. * | Value | Type | Description |
  30361. * | ----- | ------------------ | ----------- |
  30362. * | 0 | CLAMP_ADDRESSMODE | |
  30363. * | 1 | WRAP_ADDRESSMODE | |
  30364. * | 2 | MIRROR_ADDRESSMODE | |
  30365. */
  30366. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30367. /**
  30368. * | Value | Type | Description |
  30369. * | ----- | ------------------ | ----------- |
  30370. * | 0 | CLAMP_ADDRESSMODE | |
  30371. * | 1 | WRAP_ADDRESSMODE | |
  30372. * | 2 | MIRROR_ADDRESSMODE | |
  30373. */
  30374. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30375. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30376. this.isCube = false;
  30377. this.is3D = false;
  30378. this.gammaSpace = true;
  30379. this.invertZ = false;
  30380. this.lodLevelInAlpha = false;
  30381. this.isRenderTarget = false;
  30382. this.animations = new Array();
  30383. /**
  30384. * An event triggered when the texture is disposed.
  30385. */
  30386. this.onDisposeObservable = new BABYLON.Observable();
  30387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30388. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30389. if (this._scene) {
  30390. this._scene.textures.push(this);
  30391. }
  30392. this._uid = null;
  30393. }
  30394. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30395. get: function () {
  30396. return this._hasAlpha;
  30397. },
  30398. set: function (value) {
  30399. if (this._hasAlpha === value) {
  30400. return;
  30401. }
  30402. this._hasAlpha = value;
  30403. if (this._scene) {
  30404. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30405. }
  30406. },
  30407. enumerable: true,
  30408. configurable: true
  30409. });
  30410. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30411. get: function () {
  30412. return this._coordinatesMode;
  30413. },
  30414. /**
  30415. * How a texture is mapped.
  30416. *
  30417. * | Value | Type | Description |
  30418. * | ----- | ----------------------------------- | ----------- |
  30419. * | 0 | EXPLICIT_MODE | |
  30420. * | 1 | SPHERICAL_MODE | |
  30421. * | 2 | PLANAR_MODE | |
  30422. * | 3 | CUBIC_MODE | |
  30423. * | 4 | PROJECTION_MODE | |
  30424. * | 5 | SKYBOX_MODE | |
  30425. * | 6 | INVCUBIC_MODE | |
  30426. * | 7 | EQUIRECTANGULAR_MODE | |
  30427. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30428. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30429. */
  30430. set: function (value) {
  30431. if (this._coordinatesMode === value) {
  30432. return;
  30433. }
  30434. this._coordinatesMode = value;
  30435. if (this._scene) {
  30436. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30437. }
  30438. },
  30439. enumerable: true,
  30440. configurable: true
  30441. });
  30442. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30443. /**
  30444. * Gets whether or not the texture contains RGBD data.
  30445. */
  30446. get: function () {
  30447. return this._texture != null && this._texture._isRGBD;
  30448. },
  30449. enumerable: true,
  30450. configurable: true
  30451. });
  30452. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30453. get: function () {
  30454. if (this._texture)
  30455. return this._texture._lodGenerationOffset;
  30456. return 0.0;
  30457. },
  30458. set: function (value) {
  30459. if (this._texture)
  30460. this._texture._lodGenerationOffset = value;
  30461. },
  30462. enumerable: true,
  30463. configurable: true
  30464. });
  30465. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30466. get: function () {
  30467. if (this._texture)
  30468. return this._texture._lodGenerationScale;
  30469. return 0.0;
  30470. },
  30471. set: function (value) {
  30472. if (this._texture)
  30473. this._texture._lodGenerationScale = value;
  30474. },
  30475. enumerable: true,
  30476. configurable: true
  30477. });
  30478. Object.defineProperty(BaseTexture.prototype, "uid", {
  30479. get: function () {
  30480. if (!this._uid) {
  30481. this._uid = BABYLON.Tools.RandomId();
  30482. }
  30483. return this._uid;
  30484. },
  30485. enumerable: true,
  30486. configurable: true
  30487. });
  30488. BaseTexture.prototype.toString = function () {
  30489. return this.name;
  30490. };
  30491. BaseTexture.prototype.getClassName = function () {
  30492. return "BaseTexture";
  30493. };
  30494. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30495. set: function (callback) {
  30496. if (this._onDisposeObserver) {
  30497. this.onDisposeObservable.remove(this._onDisposeObserver);
  30498. }
  30499. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30500. },
  30501. enumerable: true,
  30502. configurable: true
  30503. });
  30504. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30505. get: function () {
  30506. return true;
  30507. },
  30508. enumerable: true,
  30509. configurable: true
  30510. });
  30511. BaseTexture.prototype.getScene = function () {
  30512. return this._scene;
  30513. };
  30514. BaseTexture.prototype.getTextureMatrix = function () {
  30515. return BABYLON.Matrix.IdentityReadOnly;
  30516. };
  30517. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30518. return BABYLON.Matrix.IdentityReadOnly;
  30519. };
  30520. BaseTexture.prototype.getInternalTexture = function () {
  30521. return this._texture;
  30522. };
  30523. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30524. return !this.isBlocking || this.isReady();
  30525. };
  30526. BaseTexture.prototype.isReady = function () {
  30527. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30528. this.delayLoad();
  30529. return false;
  30530. }
  30531. if (this._texture) {
  30532. return this._texture.isReady;
  30533. }
  30534. return false;
  30535. };
  30536. BaseTexture.prototype.getSize = function () {
  30537. if (this._texture && this._texture.width) {
  30538. return new BABYLON.Size(this._texture.width, this._texture.height);
  30539. }
  30540. if (this._texture && this._texture._size) {
  30541. return new BABYLON.Size(this._texture._size, this._texture._size);
  30542. }
  30543. return BABYLON.Size.Zero();
  30544. };
  30545. BaseTexture.prototype.getBaseSize = function () {
  30546. if (!this.isReady() || !this._texture)
  30547. return BABYLON.Size.Zero();
  30548. if (this._texture._size) {
  30549. return new BABYLON.Size(this._texture._size, this._texture._size);
  30550. }
  30551. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30552. };
  30553. BaseTexture.prototype.scale = function (ratio) {
  30554. };
  30555. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30556. get: function () {
  30557. return false;
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30563. if (!this._scene) {
  30564. return null;
  30565. }
  30566. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30567. for (var index = 0; index < texturesCache.length; index++) {
  30568. var texturesCacheEntry = texturesCache[index];
  30569. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30570. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30571. texturesCacheEntry.incrementReferences();
  30572. return texturesCacheEntry;
  30573. }
  30574. }
  30575. }
  30576. return null;
  30577. };
  30578. BaseTexture.prototype._rebuild = function () {
  30579. };
  30580. BaseTexture.prototype.delayLoad = function () {
  30581. };
  30582. BaseTexture.prototype.clone = function () {
  30583. return null;
  30584. };
  30585. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30586. get: function () {
  30587. if (!this._texture) {
  30588. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30589. }
  30590. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30591. },
  30592. enumerable: true,
  30593. configurable: true
  30594. });
  30595. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30596. get: function () {
  30597. if (!this._texture) {
  30598. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30599. }
  30600. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30601. },
  30602. enumerable: true,
  30603. configurable: true
  30604. });
  30605. /**
  30606. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30607. * This will returns an RGBA array buffer containing either in values (0-255) or
  30608. * float values (0-1) depending of the underlying buffer type.
  30609. * @param faceIndex The face of the texture to read (in case of cube texture)
  30610. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30611. * @returns The Array buffer containing the pixels data.
  30612. */
  30613. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30614. if (faceIndex === void 0) { faceIndex = 0; }
  30615. if (level === void 0) { level = 0; }
  30616. if (!this._texture) {
  30617. return null;
  30618. }
  30619. var size = this.getSize();
  30620. var width = size.width;
  30621. var height = size.height;
  30622. var scene = this.getScene();
  30623. if (!scene) {
  30624. return null;
  30625. }
  30626. var engine = scene.getEngine();
  30627. if (level != 0) {
  30628. width = width / Math.pow(2, level);
  30629. height = height / Math.pow(2, level);
  30630. width = Math.round(width);
  30631. height = Math.round(height);
  30632. }
  30633. if (this._texture.isCube) {
  30634. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30635. }
  30636. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30637. };
  30638. BaseTexture.prototype.releaseInternalTexture = function () {
  30639. if (this._texture) {
  30640. this._texture.dispose();
  30641. this._texture = null;
  30642. }
  30643. };
  30644. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30645. get: function () {
  30646. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30647. return null;
  30648. }
  30649. if (!this._texture._sphericalPolynomial) {
  30650. this._texture._sphericalPolynomial =
  30651. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30652. }
  30653. return this._texture._sphericalPolynomial;
  30654. },
  30655. set: function (value) {
  30656. if (this._texture) {
  30657. this._texture._sphericalPolynomial = value;
  30658. }
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30664. get: function () {
  30665. if (this._texture) {
  30666. return this._texture._lodTextureHigh;
  30667. }
  30668. return null;
  30669. },
  30670. enumerable: true,
  30671. configurable: true
  30672. });
  30673. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30674. get: function () {
  30675. if (this._texture) {
  30676. return this._texture._lodTextureMid;
  30677. }
  30678. return null;
  30679. },
  30680. enumerable: true,
  30681. configurable: true
  30682. });
  30683. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30684. get: function () {
  30685. if (this._texture) {
  30686. return this._texture._lodTextureLow;
  30687. }
  30688. return null;
  30689. },
  30690. enumerable: true,
  30691. configurable: true
  30692. });
  30693. BaseTexture.prototype.dispose = function () {
  30694. if (!this._scene) {
  30695. return;
  30696. }
  30697. // Animations
  30698. this._scene.stopAnimation(this);
  30699. // Remove from scene
  30700. this._scene._removePendingData(this);
  30701. var index = this._scene.textures.indexOf(this);
  30702. if (index >= 0) {
  30703. this._scene.textures.splice(index, 1);
  30704. }
  30705. if (this._texture === undefined) {
  30706. return;
  30707. }
  30708. // Release
  30709. this.releaseInternalTexture();
  30710. // Callback
  30711. this.onDisposeObservable.notifyObservers(this);
  30712. this.onDisposeObservable.clear();
  30713. };
  30714. BaseTexture.prototype.serialize = function () {
  30715. if (!this.name) {
  30716. return null;
  30717. }
  30718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30719. // Animations
  30720. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30721. return serializationObject;
  30722. };
  30723. BaseTexture.WhenAllReady = function (textures, callback) {
  30724. var numRemaining = textures.length;
  30725. if (numRemaining === 0) {
  30726. callback();
  30727. return;
  30728. }
  30729. var _loop_1 = function () {
  30730. texture = textures[i];
  30731. if (texture.isReady()) {
  30732. if (--numRemaining === 0) {
  30733. callback();
  30734. }
  30735. }
  30736. else {
  30737. onLoadObservable = texture.onLoadObservable;
  30738. var onLoadCallback_1 = function () {
  30739. onLoadObservable.removeCallback(onLoadCallback_1);
  30740. if (--numRemaining === 0) {
  30741. callback();
  30742. }
  30743. };
  30744. onLoadObservable.add(onLoadCallback_1);
  30745. }
  30746. };
  30747. var texture, onLoadObservable;
  30748. for (var i = 0; i < textures.length; i++) {
  30749. _loop_1();
  30750. }
  30751. };
  30752. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30753. __decorate([
  30754. BABYLON.serialize()
  30755. ], BaseTexture.prototype, "name", void 0);
  30756. __decorate([
  30757. BABYLON.serialize("hasAlpha")
  30758. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30759. __decorate([
  30760. BABYLON.serialize()
  30761. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], BaseTexture.prototype, "level", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30768. __decorate([
  30769. BABYLON.serialize("coordinatesMode")
  30770. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], BaseTexture.prototype, "wrapU", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], BaseTexture.prototype, "wrapV", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], BaseTexture.prototype, "wrapR", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], BaseTexture.prototype, "isCube", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], BaseTexture.prototype, "is3D", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], BaseTexture.prototype, "gammaSpace", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], BaseTexture.prototype, "invertZ", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], BaseTexture.prototype, "lodGenerationScale", null);
  30804. __decorate([
  30805. BABYLON.serialize()
  30806. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30807. return BaseTexture;
  30808. }());
  30809. BABYLON.BaseTexture = BaseTexture;
  30810. })(BABYLON || (BABYLON = {}));
  30811. //# sourceMappingURL=babylon.baseTexture.js.map
  30812. var BABYLON;
  30813. (function (BABYLON) {
  30814. var Texture = /** @class */ (function (_super) {
  30815. __extends(Texture, _super);
  30816. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30817. if (noMipmap === void 0) { noMipmap = false; }
  30818. if (invertY === void 0) { invertY = true; }
  30819. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30820. if (onLoad === void 0) { onLoad = null; }
  30821. if (onError === void 0) { onError = null; }
  30822. if (buffer === void 0) { buffer = null; }
  30823. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30824. var _this = _super.call(this, scene) || this;
  30825. _this.uOffset = 0;
  30826. _this.vOffset = 0;
  30827. _this.uScale = 1.0;
  30828. _this.vScale = 1.0;
  30829. _this.uAng = 0;
  30830. _this.vAng = 0;
  30831. _this.wAng = 0;
  30832. /**
  30833. * Defines the center of rotation (U)
  30834. */
  30835. _this.uRotationCenter = 0.5;
  30836. /**
  30837. * Defines the center of rotation (V)
  30838. */
  30839. _this.vRotationCenter = 0.5;
  30840. /**
  30841. * Defines the center of rotation (W)
  30842. */
  30843. _this.wRotationCenter = 0.5;
  30844. _this._isBlocking = true;
  30845. _this.name = url || "";
  30846. _this.url = url;
  30847. _this._noMipmap = noMipmap;
  30848. _this._invertY = invertY;
  30849. _this._samplingMode = samplingMode;
  30850. _this._buffer = buffer;
  30851. _this._deleteBuffer = deleteBuffer;
  30852. if (format) {
  30853. _this._format = format;
  30854. }
  30855. scene = _this.getScene();
  30856. if (!scene) {
  30857. return _this;
  30858. }
  30859. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30860. var load = function () {
  30861. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30862. _this.onLoadObservable.notifyObservers(_this);
  30863. }
  30864. if (onLoad) {
  30865. onLoad();
  30866. }
  30867. if (!_this.isBlocking && scene) {
  30868. scene.resetCachedMaterial();
  30869. }
  30870. };
  30871. if (!_this.url) {
  30872. _this._delayedOnLoad = load;
  30873. _this._delayedOnError = onError;
  30874. return _this;
  30875. }
  30876. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30877. if (!_this._texture) {
  30878. if (!scene.useDelayedTextureLoading) {
  30879. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30880. if (deleteBuffer) {
  30881. delete _this._buffer;
  30882. }
  30883. }
  30884. else {
  30885. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30886. _this._delayedOnLoad = load;
  30887. _this._delayedOnError = onError;
  30888. }
  30889. }
  30890. else {
  30891. if (_this._texture.isReady) {
  30892. BABYLON.Tools.SetImmediate(function () { return load(); });
  30893. }
  30894. else {
  30895. _this._texture.onLoadedObservable.add(load);
  30896. }
  30897. }
  30898. return _this;
  30899. }
  30900. Object.defineProperty(Texture.prototype, "noMipmap", {
  30901. get: function () {
  30902. return this._noMipmap;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Object.defineProperty(Texture.prototype, "isBlocking", {
  30908. get: function () {
  30909. return this._isBlocking;
  30910. },
  30911. set: function (value) {
  30912. this._isBlocking = value;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. Object.defineProperty(Texture.prototype, "samplingMode", {
  30918. get: function () {
  30919. return this._samplingMode;
  30920. },
  30921. enumerable: true,
  30922. configurable: true
  30923. });
  30924. /**
  30925. * Update the url (and optional buffer) of this texture if url was null during construction.
  30926. * @param url the url of the texture
  30927. * @param buffer the buffer of the texture (defaults to null)
  30928. */
  30929. Texture.prototype.updateURL = function (url, buffer) {
  30930. if (buffer === void 0) { buffer = null; }
  30931. if (this.url) {
  30932. throw new Error("URL is already set");
  30933. }
  30934. this.url = url;
  30935. this._buffer = buffer;
  30936. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30937. this.delayLoad();
  30938. };
  30939. Texture.prototype.delayLoad = function () {
  30940. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30941. return;
  30942. }
  30943. var scene = this.getScene();
  30944. if (!scene) {
  30945. return;
  30946. }
  30947. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30948. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30949. if (!this._texture) {
  30950. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30951. if (this._deleteBuffer) {
  30952. delete this._buffer;
  30953. }
  30954. }
  30955. else {
  30956. if (this._delayedOnLoad) {
  30957. if (this._texture.isReady) {
  30958. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30959. }
  30960. else {
  30961. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30962. }
  30963. }
  30964. }
  30965. this._delayedOnLoad = null;
  30966. this._delayedOnError = null;
  30967. };
  30968. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30969. if (!this._texture) {
  30970. return;
  30971. }
  30972. var scene = this.getScene();
  30973. if (!scene) {
  30974. return;
  30975. }
  30976. this._samplingMode = samplingMode;
  30977. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30978. };
  30979. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30980. x *= this.uScale;
  30981. y *= this.vScale;
  30982. x -= this.uRotationCenter * this.uScale;
  30983. y -= this.vRotationCenter * this.vScale;
  30984. z -= this.wRotationCenter;
  30985. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30986. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30987. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30988. t.z += this.wRotationCenter;
  30989. };
  30990. Texture.prototype.getTextureMatrix = function () {
  30991. var _this = this;
  30992. if (this.uOffset === this._cachedUOffset &&
  30993. this.vOffset === this._cachedVOffset &&
  30994. this.uScale === this._cachedUScale &&
  30995. this.vScale === this._cachedVScale &&
  30996. this.uAng === this._cachedUAng &&
  30997. this.vAng === this._cachedVAng &&
  30998. this.wAng === this._cachedWAng) {
  30999. return this._cachedTextureMatrix;
  31000. }
  31001. this._cachedUOffset = this.uOffset;
  31002. this._cachedVOffset = this.vOffset;
  31003. this._cachedUScale = this.uScale;
  31004. this._cachedVScale = this.vScale;
  31005. this._cachedUAng = this.uAng;
  31006. this._cachedVAng = this.vAng;
  31007. this._cachedWAng = this.wAng;
  31008. if (!this._cachedTextureMatrix) {
  31009. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31010. this._rowGenerationMatrix = new BABYLON.Matrix();
  31011. this._t0 = BABYLON.Vector3.Zero();
  31012. this._t1 = BABYLON.Vector3.Zero();
  31013. this._t2 = BABYLON.Vector3.Zero();
  31014. }
  31015. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31016. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31017. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31018. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31019. this._t1.subtractInPlace(this._t0);
  31020. this._t2.subtractInPlace(this._t0);
  31021. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31022. this._cachedTextureMatrix.m[0] = this._t1.x;
  31023. this._cachedTextureMatrix.m[1] = this._t1.y;
  31024. this._cachedTextureMatrix.m[2] = this._t1.z;
  31025. this._cachedTextureMatrix.m[4] = this._t2.x;
  31026. this._cachedTextureMatrix.m[5] = this._t2.y;
  31027. this._cachedTextureMatrix.m[6] = this._t2.z;
  31028. this._cachedTextureMatrix.m[8] = this._t0.x;
  31029. this._cachedTextureMatrix.m[9] = this._t0.y;
  31030. this._cachedTextureMatrix.m[10] = this._t0.z;
  31031. var scene = this.getScene();
  31032. if (!scene) {
  31033. return this._cachedTextureMatrix;
  31034. }
  31035. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31036. return mat.hasTexture(_this);
  31037. });
  31038. return this._cachedTextureMatrix;
  31039. };
  31040. Texture.prototype.getReflectionTextureMatrix = function () {
  31041. var _this = this;
  31042. var scene = this.getScene();
  31043. if (!scene) {
  31044. return this._cachedTextureMatrix;
  31045. }
  31046. if (this.uOffset === this._cachedUOffset &&
  31047. this.vOffset === this._cachedVOffset &&
  31048. this.uScale === this._cachedUScale &&
  31049. this.vScale === this._cachedVScale &&
  31050. this.coordinatesMode === this._cachedCoordinatesMode) {
  31051. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31052. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31053. return this._cachedTextureMatrix;
  31054. }
  31055. }
  31056. else {
  31057. return this._cachedTextureMatrix;
  31058. }
  31059. }
  31060. if (!this._cachedTextureMatrix) {
  31061. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31062. }
  31063. if (!this._projectionModeMatrix) {
  31064. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31065. }
  31066. this._cachedUOffset = this.uOffset;
  31067. this._cachedVOffset = this.vOffset;
  31068. this._cachedUScale = this.uScale;
  31069. this._cachedVScale = this.vScale;
  31070. this._cachedCoordinatesMode = this.coordinatesMode;
  31071. switch (this.coordinatesMode) {
  31072. case Texture.PLANAR_MODE:
  31073. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31074. this._cachedTextureMatrix[0] = this.uScale;
  31075. this._cachedTextureMatrix[5] = this.vScale;
  31076. this._cachedTextureMatrix[12] = this.uOffset;
  31077. this._cachedTextureMatrix[13] = this.vOffset;
  31078. break;
  31079. case Texture.PROJECTION_MODE:
  31080. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31081. this._projectionModeMatrix.m[0] = 0.5;
  31082. this._projectionModeMatrix.m[5] = -0.5;
  31083. this._projectionModeMatrix.m[10] = 0.0;
  31084. this._projectionModeMatrix.m[12] = 0.5;
  31085. this._projectionModeMatrix.m[13] = 0.5;
  31086. this._projectionModeMatrix.m[14] = 1.0;
  31087. this._projectionModeMatrix.m[15] = 1.0;
  31088. var projectionMatrix = scene.getProjectionMatrix();
  31089. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31090. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31091. break;
  31092. default:
  31093. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31094. break;
  31095. }
  31096. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31097. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31098. });
  31099. return this._cachedTextureMatrix;
  31100. };
  31101. Texture.prototype.clone = function () {
  31102. var _this = this;
  31103. return BABYLON.SerializationHelper.Clone(function () {
  31104. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31105. }, this);
  31106. };
  31107. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31108. get: function () {
  31109. if (!this._onLoadObservable) {
  31110. this._onLoadObservable = new BABYLON.Observable();
  31111. }
  31112. return this._onLoadObservable;
  31113. },
  31114. enumerable: true,
  31115. configurable: true
  31116. });
  31117. Texture.prototype.serialize = function () {
  31118. var serializationObject = _super.prototype.serialize.call(this);
  31119. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31120. serializationObject.base64String = this._buffer;
  31121. serializationObject.name = serializationObject.name.replace("data:", "");
  31122. }
  31123. serializationObject.invertY = this._invertY;
  31124. serializationObject.samplingMode = this.samplingMode;
  31125. return serializationObject;
  31126. };
  31127. Texture.prototype.getClassName = function () {
  31128. return "Texture";
  31129. };
  31130. Texture.prototype.dispose = function () {
  31131. _super.prototype.dispose.call(this);
  31132. if (this.onLoadObservable) {
  31133. this.onLoadObservable.clear();
  31134. this._onLoadObservable = null;
  31135. }
  31136. this._delayedOnLoad = null;
  31137. this._delayedOnError = null;
  31138. };
  31139. // Statics
  31140. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31141. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31142. if (onLoad === void 0) { onLoad = null; }
  31143. if (onError === void 0) { onError = null; }
  31144. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31145. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31146. };
  31147. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31148. if (parsedTexture.customType) {
  31149. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31150. // Update Sampling Mode
  31151. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31152. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31153. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31154. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31155. }
  31156. }
  31157. return parsedCustomTexture;
  31158. }
  31159. if (parsedTexture.isCube) {
  31160. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31161. }
  31162. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31163. return null;
  31164. }
  31165. var texture = BABYLON.SerializationHelper.Parse(function () {
  31166. var generateMipMaps = true;
  31167. if (parsedTexture.noMipmap) {
  31168. generateMipMaps = false;
  31169. }
  31170. if (parsedTexture.mirrorPlane) {
  31171. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31172. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31173. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31174. return mirrorTexture;
  31175. }
  31176. else if (parsedTexture.isRenderTarget) {
  31177. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31178. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31179. return renderTargetTexture;
  31180. }
  31181. else {
  31182. var texture;
  31183. if (parsedTexture.base64String) {
  31184. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31185. }
  31186. else {
  31187. var url = rootUrl + parsedTexture.name;
  31188. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31189. url = parsedTexture.url;
  31190. }
  31191. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31192. }
  31193. return texture;
  31194. }
  31195. }, parsedTexture, scene);
  31196. // Update Sampling Mode
  31197. if (parsedTexture.samplingMode) {
  31198. var sampling = parsedTexture.samplingMode;
  31199. if (texture._samplingMode !== sampling) {
  31200. texture.updateSamplingMode(sampling);
  31201. }
  31202. }
  31203. // Animations
  31204. if (parsedTexture.animations) {
  31205. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31206. var parsedAnimation = parsedTexture.animations[animationIndex];
  31207. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31208. }
  31209. }
  31210. return texture;
  31211. };
  31212. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31213. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31214. if (noMipmap === void 0) { noMipmap = false; }
  31215. if (invertY === void 0) { invertY = true; }
  31216. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31217. if (onLoad === void 0) { onLoad = null; }
  31218. if (onError === void 0) { onError = null; }
  31219. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31220. if (name.substr(0, 5) !== "data:") {
  31221. name = "data:" + name;
  31222. }
  31223. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31224. };
  31225. // Constants
  31226. Texture.NEAREST_SAMPLINGMODE = 1;
  31227. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31228. Texture.BILINEAR_SAMPLINGMODE = 2;
  31229. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31230. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31231. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31232. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31233. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31234. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31235. Texture.NEAREST_LINEAR = 7;
  31236. Texture.NEAREST_NEAREST = 8;
  31237. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31238. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31239. Texture.LINEAR_LINEAR = 11;
  31240. Texture.LINEAR_NEAREST = 12;
  31241. Texture.EXPLICIT_MODE = 0;
  31242. Texture.SPHERICAL_MODE = 1;
  31243. Texture.PLANAR_MODE = 2;
  31244. Texture.CUBIC_MODE = 3;
  31245. Texture.PROJECTION_MODE = 4;
  31246. Texture.SKYBOX_MODE = 5;
  31247. Texture.INVCUBIC_MODE = 6;
  31248. Texture.EQUIRECTANGULAR_MODE = 7;
  31249. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31250. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31251. Texture.CLAMP_ADDRESSMODE = 0;
  31252. Texture.WRAP_ADDRESSMODE = 1;
  31253. Texture.MIRROR_ADDRESSMODE = 2;
  31254. /**
  31255. * 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
  31256. */
  31257. Texture.UseSerializedUrlIfAny = false;
  31258. __decorate([
  31259. BABYLON.serialize()
  31260. ], Texture.prototype, "url", void 0);
  31261. __decorate([
  31262. BABYLON.serialize()
  31263. ], Texture.prototype, "uOffset", void 0);
  31264. __decorate([
  31265. BABYLON.serialize()
  31266. ], Texture.prototype, "vOffset", void 0);
  31267. __decorate([
  31268. BABYLON.serialize()
  31269. ], Texture.prototype, "uScale", void 0);
  31270. __decorate([
  31271. BABYLON.serialize()
  31272. ], Texture.prototype, "vScale", void 0);
  31273. __decorate([
  31274. BABYLON.serialize()
  31275. ], Texture.prototype, "uAng", void 0);
  31276. __decorate([
  31277. BABYLON.serialize()
  31278. ], Texture.prototype, "vAng", void 0);
  31279. __decorate([
  31280. BABYLON.serialize()
  31281. ], Texture.prototype, "wAng", void 0);
  31282. __decorate([
  31283. BABYLON.serialize()
  31284. ], Texture.prototype, "uRotationCenter", void 0);
  31285. __decorate([
  31286. BABYLON.serialize()
  31287. ], Texture.prototype, "vRotationCenter", void 0);
  31288. __decorate([
  31289. BABYLON.serialize()
  31290. ], Texture.prototype, "wRotationCenter", void 0);
  31291. __decorate([
  31292. BABYLON.serialize()
  31293. ], Texture.prototype, "isBlocking", null);
  31294. return Texture;
  31295. }(BABYLON.BaseTexture));
  31296. BABYLON.Texture = Texture;
  31297. })(BABYLON || (BABYLON = {}));
  31298. //# sourceMappingURL=babylon.texture.js.map
  31299. var BABYLON;
  31300. (function (BABYLON) {
  31301. /**
  31302. * @hidden
  31303. **/
  31304. var _InstancesBatch = /** @class */ (function () {
  31305. function _InstancesBatch() {
  31306. this.mustReturn = false;
  31307. this.visibleInstances = new Array();
  31308. this.renderSelf = new Array();
  31309. }
  31310. return _InstancesBatch;
  31311. }());
  31312. BABYLON._InstancesBatch = _InstancesBatch;
  31313. var Mesh = /** @class */ (function (_super) {
  31314. __extends(Mesh, _super);
  31315. /**
  31316. * @constructor
  31317. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31318. * @param {Scene} scene The scene to add this mesh to.
  31319. * @param {Node} parent The parent of this mesh, if it has one
  31320. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31321. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31322. * When false, achieved by calling a clone(), also passing False.
  31323. * This will make creation of children, recursive.
  31324. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31325. */
  31326. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31327. if (scene === void 0) { scene = null; }
  31328. if (parent === void 0) { parent = null; }
  31329. if (source === void 0) { source = null; }
  31330. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31331. var _this = _super.call(this, name, scene) || this;
  31332. // Events
  31333. /**
  31334. * An event triggered before rendering the mesh
  31335. */
  31336. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31337. /**
  31338. * An event triggered after rendering the mesh
  31339. */
  31340. _this.onAfterRenderObservable = new BABYLON.Observable();
  31341. /**
  31342. * An event triggered before drawing the mesh
  31343. */
  31344. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31345. // Members
  31346. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31347. _this.instances = new Array();
  31348. _this._LODLevels = new Array();
  31349. _this._visibleInstances = {};
  31350. _this._renderIdForInstances = new Array();
  31351. _this._batchCache = new _InstancesBatch();
  31352. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31353. // Use by builder only to know what orientation were the mesh build in.
  31354. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31355. _this.overrideMaterialSideOrientation = null;
  31356. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31357. // Will be used to save a source mesh reference, If any
  31358. _this._source = null;
  31359. scene = _this.getScene();
  31360. if (source) {
  31361. // Geometry
  31362. if (source._geometry) {
  31363. source._geometry.applyToMesh(_this);
  31364. }
  31365. // Deep copy
  31366. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31367. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31368. // Source mesh
  31369. _this._source = source;
  31370. // Metadata
  31371. if (source.metadata && source.metadata.clone) {
  31372. _this.metadata = source.metadata.clone();
  31373. }
  31374. else {
  31375. _this.metadata = source.metadata;
  31376. }
  31377. // Tags
  31378. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31379. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31380. }
  31381. // Parent
  31382. _this.parent = source.parent;
  31383. // Pivot
  31384. _this.setPivotMatrix(source.getPivotMatrix());
  31385. _this.id = name + "." + source.id;
  31386. // Material
  31387. _this.material = source.material;
  31388. var index;
  31389. if (!doNotCloneChildren) {
  31390. // Children
  31391. var directDescendants = source.getDescendants(true);
  31392. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31393. var child = directDescendants[index_1];
  31394. if (child.clone) {
  31395. child.clone(name + "." + child.name, _this);
  31396. }
  31397. }
  31398. }
  31399. // Physics clone
  31400. var physicsEngine = _this.getScene().getPhysicsEngine();
  31401. if (clonePhysicsImpostor && physicsEngine) {
  31402. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31403. if (impostor) {
  31404. _this.physicsImpostor = impostor.clone(_this);
  31405. }
  31406. }
  31407. // Particles
  31408. for (index = 0; index < scene.particleSystems.length; index++) {
  31409. var system = scene.particleSystems[index];
  31410. if (system.emitter === source) {
  31411. system.clone(system.name, _this);
  31412. }
  31413. }
  31414. _this.computeWorldMatrix(true);
  31415. }
  31416. // Parent
  31417. if (parent !== null) {
  31418. _this.parent = parent;
  31419. }
  31420. return _this;
  31421. }
  31422. Object.defineProperty(Mesh, "FRONTSIDE", {
  31423. /**
  31424. * Mesh side orientation : usually the external or front surface
  31425. */
  31426. get: function () {
  31427. return Mesh._FRONTSIDE;
  31428. },
  31429. enumerable: true,
  31430. configurable: true
  31431. });
  31432. Object.defineProperty(Mesh, "BACKSIDE", {
  31433. /**
  31434. * Mesh side orientation : usually the internal or back surface
  31435. */
  31436. get: function () {
  31437. return Mesh._BACKSIDE;
  31438. },
  31439. enumerable: true,
  31440. configurable: true
  31441. });
  31442. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31443. /**
  31444. * Mesh side orientation : both internal and external or front and back surfaces
  31445. */
  31446. get: function () {
  31447. return Mesh._DOUBLESIDE;
  31448. },
  31449. enumerable: true,
  31450. configurable: true
  31451. });
  31452. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31453. /**
  31454. * Mesh side orientation : by default, `FRONTSIDE`
  31455. */
  31456. get: function () {
  31457. return Mesh._DEFAULTSIDE;
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. Object.defineProperty(Mesh, "NO_CAP", {
  31463. /**
  31464. * Mesh cap setting : no cap
  31465. */
  31466. get: function () {
  31467. return Mesh._NO_CAP;
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Object.defineProperty(Mesh, "CAP_START", {
  31473. /**
  31474. * Mesh cap setting : one cap at the beginning of the mesh
  31475. */
  31476. get: function () {
  31477. return Mesh._CAP_START;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(Mesh, "CAP_END", {
  31483. /**
  31484. * Mesh cap setting : one cap at the end of the mesh
  31485. */
  31486. get: function () {
  31487. return Mesh._CAP_END;
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. Object.defineProperty(Mesh, "CAP_ALL", {
  31493. /**
  31494. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31495. */
  31496. get: function () {
  31497. return Mesh._CAP_ALL;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31503. set: function (callback) {
  31504. if (this._onBeforeDrawObserver) {
  31505. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31506. }
  31507. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31508. },
  31509. enumerable: true,
  31510. configurable: true
  31511. });
  31512. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31513. get: function () {
  31514. return this._morphTargetManager;
  31515. },
  31516. set: function (value) {
  31517. if (this._morphTargetManager === value) {
  31518. return;
  31519. }
  31520. this._morphTargetManager = value;
  31521. this._syncGeometryWithMorphTargetManager();
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Mesh.prototype, "source", {
  31527. get: function () {
  31528. return this._source;
  31529. },
  31530. enumerable: true,
  31531. configurable: true
  31532. });
  31533. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31534. get: function () {
  31535. return this._unIndexed;
  31536. },
  31537. set: function (value) {
  31538. if (this._unIndexed !== value) {
  31539. this._unIndexed = value;
  31540. this._markSubMeshesAsAttributesDirty();
  31541. }
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. // Methods
  31547. /**
  31548. * Returns the string "Mesh".
  31549. */
  31550. Mesh.prototype.getClassName = function () {
  31551. return "Mesh";
  31552. };
  31553. /**
  31554. * Returns a string.
  31555. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31556. */
  31557. Mesh.prototype.toString = function (fullDetails) {
  31558. var ret = _super.prototype.toString.call(this, fullDetails);
  31559. ret += ", n vertices: " + this.getTotalVertices();
  31560. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31561. if (this.animations) {
  31562. for (var i = 0; i < this.animations.length; i++) {
  31563. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31564. }
  31565. }
  31566. if (fullDetails) {
  31567. if (this._geometry) {
  31568. var ib = this.getIndices();
  31569. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31570. if (vb && ib) {
  31571. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31572. }
  31573. }
  31574. else {
  31575. ret += ", flat shading: UNKNOWN";
  31576. }
  31577. }
  31578. return ret;
  31579. };
  31580. Mesh.prototype._unBindEffect = function () {
  31581. _super.prototype._unBindEffect.call(this);
  31582. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31583. var instance = _a[_i];
  31584. instance._unBindEffect();
  31585. }
  31586. };
  31587. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31588. /**
  31589. * True if the mesh has some Levels Of Details (LOD).
  31590. * Returns a boolean.
  31591. */
  31592. get: function () {
  31593. return this._LODLevels.length > 0;
  31594. },
  31595. enumerable: true,
  31596. configurable: true
  31597. });
  31598. /**
  31599. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31600. * @returns an array of {BABYLON.MeshLODLevel}
  31601. */
  31602. Mesh.prototype.getLODLevels = function () {
  31603. return this._LODLevels;
  31604. };
  31605. Mesh.prototype._sortLODLevels = function () {
  31606. this._LODLevels.sort(function (a, b) {
  31607. if (a.distance < b.distance) {
  31608. return 1;
  31609. }
  31610. if (a.distance > b.distance) {
  31611. return -1;
  31612. }
  31613. return 0;
  31614. });
  31615. };
  31616. /**
  31617. * Add a mesh as LOD level triggered at the given distance.
  31618. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31619. * @param distance The distance from the center of the object to show this level
  31620. * @param mesh The mesh to be added as LOD level (can be null)
  31621. * @return This mesh (for chaining)
  31622. */
  31623. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31624. if (mesh && mesh._masterMesh) {
  31625. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31626. return this;
  31627. }
  31628. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31629. this._LODLevels.push(level);
  31630. if (mesh) {
  31631. mesh._masterMesh = this;
  31632. }
  31633. this._sortLODLevels();
  31634. return this;
  31635. };
  31636. /**
  31637. * Returns the LOD level mesh at the passed distance or null if not found.
  31638. * It is related to the method `addLODLevel(distance, mesh)`.
  31639. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31640. * Returns an object Mesh or `null`.
  31641. */
  31642. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31643. for (var index = 0; index < this._LODLevels.length; index++) {
  31644. var level = this._LODLevels[index];
  31645. if (level.distance === distance) {
  31646. return level.mesh;
  31647. }
  31648. }
  31649. return null;
  31650. };
  31651. /**
  31652. * Remove a mesh from the LOD array
  31653. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31654. * @param {Mesh} mesh The mesh to be removed.
  31655. * @return {Mesh} This mesh (for chaining)
  31656. */
  31657. Mesh.prototype.removeLODLevel = function (mesh) {
  31658. for (var index = 0; index < this._LODLevels.length; index++) {
  31659. if (this._LODLevels[index].mesh === mesh) {
  31660. this._LODLevels.splice(index, 1);
  31661. if (mesh) {
  31662. mesh._masterMesh = null;
  31663. }
  31664. }
  31665. }
  31666. this._sortLODLevels();
  31667. return this;
  31668. };
  31669. /**
  31670. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31671. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31672. */
  31673. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31674. if (!this._LODLevels || this._LODLevels.length === 0) {
  31675. return this;
  31676. }
  31677. var bSphere;
  31678. if (boundingSphere) {
  31679. bSphere = boundingSphere;
  31680. }
  31681. else {
  31682. var boundingInfo = this.getBoundingInfo();
  31683. bSphere = boundingInfo.boundingSphere;
  31684. }
  31685. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31686. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31687. if (this.onLODLevelSelection) {
  31688. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31689. }
  31690. return this;
  31691. }
  31692. for (var index = 0; index < this._LODLevels.length; index++) {
  31693. var level = this._LODLevels[index];
  31694. if (level.distance < distanceToCamera) {
  31695. if (level.mesh) {
  31696. level.mesh._preActivate();
  31697. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31698. }
  31699. if (this.onLODLevelSelection) {
  31700. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31701. }
  31702. return level.mesh;
  31703. }
  31704. }
  31705. if (this.onLODLevelSelection) {
  31706. this.onLODLevelSelection(distanceToCamera, this, this);
  31707. }
  31708. return this;
  31709. };
  31710. Object.defineProperty(Mesh.prototype, "geometry", {
  31711. /**
  31712. * Returns the mesh internal Geometry object.
  31713. */
  31714. get: function () {
  31715. return this._geometry;
  31716. },
  31717. enumerable: true,
  31718. configurable: true
  31719. });
  31720. /**
  31721. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31722. */
  31723. Mesh.prototype.getTotalVertices = function () {
  31724. if (this._geometry === null || this._geometry === undefined) {
  31725. return 0;
  31726. }
  31727. return this._geometry.getTotalVertices();
  31728. };
  31729. /**
  31730. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31731. * 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.
  31732. * You can force the copy with forceCopy === true
  31733. * Returns null if the mesh has no geometry or no vertex buffer.
  31734. * Possible `kind` values :
  31735. * - BABYLON.VertexBuffer.PositionKind
  31736. * - BABYLON.VertexBuffer.UVKind
  31737. * - BABYLON.VertexBuffer.UV2Kind
  31738. * - BABYLON.VertexBuffer.UV3Kind
  31739. * - BABYLON.VertexBuffer.UV4Kind
  31740. * - BABYLON.VertexBuffer.UV5Kind
  31741. * - BABYLON.VertexBuffer.UV6Kind
  31742. * - BABYLON.VertexBuffer.ColorKind
  31743. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31744. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31745. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31746. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31747. */
  31748. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31749. if (!this._geometry) {
  31750. return null;
  31751. }
  31752. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31753. };
  31754. /**
  31755. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31756. * Returns `null` if the mesh has no geometry.
  31757. * Possible `kind` values :
  31758. * - BABYLON.VertexBuffer.PositionKind
  31759. * - BABYLON.VertexBuffer.UVKind
  31760. * - BABYLON.VertexBuffer.UV2Kind
  31761. * - BABYLON.VertexBuffer.UV3Kind
  31762. * - BABYLON.VertexBuffer.UV4Kind
  31763. * - BABYLON.VertexBuffer.UV5Kind
  31764. * - BABYLON.VertexBuffer.UV6Kind
  31765. * - BABYLON.VertexBuffer.ColorKind
  31766. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31767. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31768. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31769. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31770. */
  31771. Mesh.prototype.getVertexBuffer = function (kind) {
  31772. if (!this._geometry) {
  31773. return null;
  31774. }
  31775. return this._geometry.getVertexBuffer(kind);
  31776. };
  31777. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31778. if (!this._geometry) {
  31779. if (this._delayInfo) {
  31780. return this._delayInfo.indexOf(kind) !== -1;
  31781. }
  31782. return false;
  31783. }
  31784. return this._geometry.isVerticesDataPresent(kind);
  31785. };
  31786. /**
  31787. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31788. * Possible `kind` values :
  31789. * - BABYLON.VertexBuffer.PositionKind
  31790. * - BABYLON.VertexBuffer.UVKind
  31791. * - BABYLON.VertexBuffer.UV2Kind
  31792. * - BABYLON.VertexBuffer.UV3Kind
  31793. * - BABYLON.VertexBuffer.UV4Kind
  31794. * - BABYLON.VertexBuffer.UV5Kind
  31795. * - BABYLON.VertexBuffer.UV6Kind
  31796. * - BABYLON.VertexBuffer.ColorKind
  31797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31801. */
  31802. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31803. if (!this._geometry) {
  31804. if (this._delayInfo) {
  31805. return this._delayInfo.indexOf(kind) !== -1;
  31806. }
  31807. return false;
  31808. }
  31809. return this._geometry.isVertexBufferUpdatable(kind);
  31810. };
  31811. /**
  31812. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31813. * Possible `kind` values :
  31814. * - BABYLON.VertexBuffer.PositionKind
  31815. * - BABYLON.VertexBuffer.UVKind
  31816. * - BABYLON.VertexBuffer.UV2Kind
  31817. * - BABYLON.VertexBuffer.UV3Kind
  31818. * - BABYLON.VertexBuffer.UV4Kind
  31819. * - BABYLON.VertexBuffer.UV5Kind
  31820. * - BABYLON.VertexBuffer.UV6Kind
  31821. * - BABYLON.VertexBuffer.ColorKind
  31822. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31823. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31824. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31825. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31826. */
  31827. Mesh.prototype.getVerticesDataKinds = function () {
  31828. if (!this._geometry) {
  31829. var result = new Array();
  31830. if (this._delayInfo) {
  31831. this._delayInfo.forEach(function (kind, index, array) {
  31832. result.push(kind);
  31833. });
  31834. }
  31835. return result;
  31836. }
  31837. return this._geometry.getVerticesDataKinds();
  31838. };
  31839. /**
  31840. * Returns a positive integer : the total number of indices in this mesh geometry.
  31841. * Returns zero if the mesh has no geometry.
  31842. */
  31843. Mesh.prototype.getTotalIndices = function () {
  31844. if (!this._geometry) {
  31845. return 0;
  31846. }
  31847. return this._geometry.getTotalIndices();
  31848. };
  31849. /**
  31850. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31851. * 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.
  31852. * Returns an empty array if the mesh has no geometry.
  31853. */
  31854. Mesh.prototype.getIndices = function (copyWhenShared) {
  31855. if (!this._geometry) {
  31856. return [];
  31857. }
  31858. return this._geometry.getIndices(copyWhenShared);
  31859. };
  31860. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31861. get: function () {
  31862. return this._masterMesh !== null && this._masterMesh !== undefined;
  31863. },
  31864. enumerable: true,
  31865. configurable: true
  31866. });
  31867. /**
  31868. * Determine if the current mesh is ready to be rendered
  31869. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31870. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31871. * @returns true if all associated assets are ready (material, textures, shaders)
  31872. */
  31873. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31874. if (completeCheck === void 0) { completeCheck = false; }
  31875. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31876. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31877. return false;
  31878. }
  31879. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31880. return false;
  31881. }
  31882. if (!this.subMeshes || this.subMeshes.length === 0) {
  31883. return true;
  31884. }
  31885. if (!completeCheck) {
  31886. return true;
  31887. }
  31888. var engine = this.getEngine();
  31889. var scene = this.getScene();
  31890. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31891. this.computeWorldMatrix();
  31892. var mat = this.material || scene.defaultMaterial;
  31893. if (mat) {
  31894. if (mat.storeEffectOnSubMeshes) {
  31895. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31896. var subMesh = _a[_i];
  31897. var effectiveMaterial = subMesh.getMaterial();
  31898. if (effectiveMaterial) {
  31899. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31900. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31901. return false;
  31902. }
  31903. }
  31904. else {
  31905. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31906. return false;
  31907. }
  31908. }
  31909. }
  31910. }
  31911. }
  31912. else {
  31913. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31914. return false;
  31915. }
  31916. }
  31917. }
  31918. // Shadows
  31919. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31920. var light = _c[_b];
  31921. var generator = light.getShadowGenerator();
  31922. if (generator) {
  31923. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31924. var subMesh = _e[_d];
  31925. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31926. return false;
  31927. }
  31928. }
  31929. }
  31930. }
  31931. // LOD
  31932. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31933. var lod = _g[_f];
  31934. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31935. return false;
  31936. }
  31937. }
  31938. return true;
  31939. };
  31940. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31941. /**
  31942. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31943. * This property is pertinent only for updatable parametric shapes.
  31944. */
  31945. get: function () {
  31946. return this._areNormalsFrozen;
  31947. },
  31948. enumerable: true,
  31949. configurable: true
  31950. });
  31951. /**
  31952. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31953. * It has no effect at all on other shapes.
  31954. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31955. * Returns the Mesh.
  31956. */
  31957. Mesh.prototype.freezeNormals = function () {
  31958. this._areNormalsFrozen = true;
  31959. return this;
  31960. };
  31961. /**
  31962. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31963. * It has no effect at all on other shapes.
  31964. * It reactivates the mesh normals computation if it was previously frozen.
  31965. * Returns the Mesh.
  31966. */
  31967. Mesh.prototype.unfreezeNormals = function () {
  31968. this._areNormalsFrozen = false;
  31969. return this;
  31970. };
  31971. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31972. /**
  31973. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31974. */
  31975. set: function (count) {
  31976. this._overridenInstanceCount = count;
  31977. },
  31978. enumerable: true,
  31979. configurable: true
  31980. });
  31981. // Methods
  31982. Mesh.prototype._preActivate = function () {
  31983. var sceneRenderId = this.getScene().getRenderId();
  31984. if (this._preActivateId === sceneRenderId) {
  31985. return this;
  31986. }
  31987. this._preActivateId = sceneRenderId;
  31988. this._visibleInstances = null;
  31989. return this;
  31990. };
  31991. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31992. if (this._visibleInstances) {
  31993. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31994. }
  31995. return this;
  31996. };
  31997. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31998. if (!this._visibleInstances) {
  31999. this._visibleInstances = {};
  32000. this._visibleInstances.defaultRenderId = renderId;
  32001. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32002. }
  32003. if (!this._visibleInstances[renderId]) {
  32004. this._visibleInstances[renderId] = new Array();
  32005. }
  32006. this._visibleInstances[renderId].push(instance);
  32007. return this;
  32008. };
  32009. /**
  32010. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32011. * This means the mesh underlying bounding box and sphere are recomputed.
  32012. * Returns the Mesh.
  32013. */
  32014. Mesh.prototype.refreshBoundingInfo = function () {
  32015. return this._refreshBoundingInfo(false);
  32016. };
  32017. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32018. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32019. return this;
  32020. }
  32021. var data = this._getPositionData(applySkeleton);
  32022. if (data) {
  32023. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32024. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32025. }
  32026. if (this.subMeshes) {
  32027. for (var index = 0; index < this.subMeshes.length; index++) {
  32028. this.subMeshes[index].refreshBoundingInfo();
  32029. }
  32030. }
  32031. this._updateBoundingInfo();
  32032. return this;
  32033. };
  32034. Mesh.prototype._getPositionData = function (applySkeleton) {
  32035. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32036. if (data && applySkeleton && this.skeleton) {
  32037. data = BABYLON.Tools.Slice(data);
  32038. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32039. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32040. if (matricesWeightsData && matricesIndicesData) {
  32041. var needExtras = this.numBoneInfluencers > 4;
  32042. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32043. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32044. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32045. var tempVector = BABYLON.Tmp.Vector3[0];
  32046. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32047. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32048. var matWeightIdx = 0;
  32049. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32050. finalMatrix.reset();
  32051. var inf;
  32052. var weight;
  32053. for (inf = 0; inf < 4; inf++) {
  32054. weight = matricesWeightsData[matWeightIdx + inf];
  32055. if (weight <= 0)
  32056. break;
  32057. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32058. finalMatrix.addToSelf(tempMatrix);
  32059. }
  32060. if (needExtras) {
  32061. for (inf = 0; inf < 4; inf++) {
  32062. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32063. if (weight <= 0)
  32064. break;
  32065. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32066. finalMatrix.addToSelf(tempMatrix);
  32067. }
  32068. }
  32069. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32070. tempVector.toArray(data, index);
  32071. }
  32072. }
  32073. }
  32074. return data;
  32075. };
  32076. Mesh.prototype._createGlobalSubMesh = function (force) {
  32077. var totalVertices = this.getTotalVertices();
  32078. if (!totalVertices || !this.getIndices()) {
  32079. return null;
  32080. }
  32081. // Check if we need to recreate the submeshes
  32082. if (this.subMeshes && this.subMeshes.length > 0) {
  32083. var ib = this.getIndices();
  32084. if (!ib) {
  32085. return null;
  32086. }
  32087. var totalIndices = ib.length;
  32088. var needToRecreate = false;
  32089. if (force) {
  32090. needToRecreate = true;
  32091. }
  32092. else {
  32093. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32094. var submesh = _a[_i];
  32095. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32096. needToRecreate = true;
  32097. break;
  32098. }
  32099. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32100. needToRecreate = true;
  32101. break;
  32102. }
  32103. }
  32104. }
  32105. if (!needToRecreate) {
  32106. return this.subMeshes[0];
  32107. }
  32108. }
  32109. this.releaseSubMeshes();
  32110. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32111. };
  32112. Mesh.prototype.subdivide = function (count) {
  32113. if (count < 1) {
  32114. return;
  32115. }
  32116. var totalIndices = this.getTotalIndices();
  32117. var subdivisionSize = (totalIndices / count) | 0;
  32118. var offset = 0;
  32119. // Ensure that subdivisionSize is a multiple of 3
  32120. while (subdivisionSize % 3 !== 0) {
  32121. subdivisionSize++;
  32122. }
  32123. this.releaseSubMeshes();
  32124. for (var index = 0; index < count; index++) {
  32125. if (offset >= totalIndices) {
  32126. break;
  32127. }
  32128. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32129. offset += subdivisionSize;
  32130. }
  32131. this.synchronizeInstances();
  32132. };
  32133. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32134. if (updatable === void 0) { updatable = false; }
  32135. if (!this._geometry) {
  32136. var vertexData = new BABYLON.VertexData();
  32137. vertexData.set(data, kind);
  32138. var scene = this.getScene();
  32139. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32140. }
  32141. else {
  32142. this._geometry.setVerticesData(kind, data, updatable, stride);
  32143. }
  32144. return this;
  32145. };
  32146. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32147. if (updatable === void 0) { updatable = true; }
  32148. var vb = this.getVertexBuffer(kind);
  32149. if (!vb || vb.isUpdatable() === updatable) {
  32150. return;
  32151. }
  32152. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32153. };
  32154. /**
  32155. * Sets the mesh VertexBuffer.
  32156. * Returns the Mesh.
  32157. */
  32158. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32159. if (!this._geometry) {
  32160. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32161. }
  32162. this._geometry.setVerticesBuffer(buffer);
  32163. return this;
  32164. };
  32165. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32166. if (!this._geometry) {
  32167. return this;
  32168. }
  32169. if (!makeItUnique) {
  32170. this._geometry.updateVerticesData(kind, data, updateExtends);
  32171. }
  32172. else {
  32173. this.makeGeometryUnique();
  32174. this.updateVerticesData(kind, data, updateExtends, false);
  32175. }
  32176. return this;
  32177. };
  32178. /**
  32179. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32180. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32181. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32182. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32183. * Returns the Mesh.
  32184. */
  32185. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32186. if (computeNormals === void 0) { computeNormals = true; }
  32187. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32188. if (!positions) {
  32189. return this;
  32190. }
  32191. positionFunction(positions);
  32192. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32193. if (computeNormals) {
  32194. var indices = this.getIndices();
  32195. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32196. if (!normals) {
  32197. return this;
  32198. }
  32199. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32200. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32201. }
  32202. return this;
  32203. };
  32204. /**
  32205. * Creates a un-shared specific occurence of the geometry for the mesh.
  32206. * Returns the Mesh.
  32207. */
  32208. Mesh.prototype.makeGeometryUnique = function () {
  32209. if (!this._geometry) {
  32210. return this;
  32211. }
  32212. var oldGeometry = this._geometry;
  32213. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32214. oldGeometry.releaseForMesh(this, true);
  32215. geometry.applyToMesh(this);
  32216. return this;
  32217. };
  32218. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32219. if (totalVertices === void 0) { totalVertices = null; }
  32220. if (updatable === void 0) { updatable = false; }
  32221. if (!this._geometry) {
  32222. var vertexData = new BABYLON.VertexData();
  32223. vertexData.indices = indices;
  32224. var scene = this.getScene();
  32225. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32226. }
  32227. else {
  32228. this._geometry.setIndices(indices, totalVertices, updatable);
  32229. }
  32230. return this;
  32231. };
  32232. /**
  32233. * Update the current index buffer
  32234. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32235. * Returns the Mesh.
  32236. */
  32237. Mesh.prototype.updateIndices = function (indices, offset) {
  32238. if (!this._geometry) {
  32239. return this;
  32240. }
  32241. this._geometry.updateIndices(indices, offset);
  32242. return this;
  32243. };
  32244. /**
  32245. * Invert the geometry to move from a right handed system to a left handed one.
  32246. * Returns the Mesh.
  32247. */
  32248. Mesh.prototype.toLeftHanded = function () {
  32249. if (!this._geometry) {
  32250. return this;
  32251. }
  32252. this._geometry.toLeftHanded();
  32253. return this;
  32254. };
  32255. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32256. if (!this._geometry) {
  32257. return this;
  32258. }
  32259. var engine = this.getScene().getEngine();
  32260. // Wireframe
  32261. var indexToBind;
  32262. if (this._unIndexed) {
  32263. indexToBind = null;
  32264. }
  32265. else {
  32266. switch (fillMode) {
  32267. case BABYLON.Material.PointFillMode:
  32268. indexToBind = null;
  32269. break;
  32270. case BABYLON.Material.WireFrameFillMode:
  32271. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32272. break;
  32273. default:
  32274. case BABYLON.Material.TriangleFillMode:
  32275. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32276. break;
  32277. }
  32278. }
  32279. // VBOs
  32280. this._geometry._bind(effect, indexToBind);
  32281. return this;
  32282. };
  32283. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32284. if (alternate === void 0) { alternate = false; }
  32285. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32286. return this;
  32287. }
  32288. this.onBeforeDrawObservable.notifyObservers(this);
  32289. var scene = this.getScene();
  32290. var engine = scene.getEngine();
  32291. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32292. // or triangles as points
  32293. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32294. }
  32295. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32296. // Triangles as wireframe
  32297. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32298. }
  32299. else {
  32300. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32301. }
  32302. if (scene._isAlternateRenderingEnabled && !alternate) {
  32303. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32304. if (!effect || !scene.activeCamera) {
  32305. return this;
  32306. }
  32307. scene._switchToAlternateCameraConfiguration(true);
  32308. this._effectiveMaterial.bindView(effect);
  32309. this._effectiveMaterial.bindViewProjection(effect);
  32310. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32311. this._draw(subMesh, fillMode, instancesCount, true);
  32312. engine.setViewport(scene.activeCamera.viewport);
  32313. scene._switchToAlternateCameraConfiguration(false);
  32314. this._effectiveMaterial.bindView(effect);
  32315. this._effectiveMaterial.bindViewProjection(effect);
  32316. }
  32317. return this;
  32318. };
  32319. /**
  32320. * Registers for this mesh a javascript function called just before the rendering process.
  32321. * This function is passed the current mesh.
  32322. * Return the Mesh.
  32323. */
  32324. Mesh.prototype.registerBeforeRender = function (func) {
  32325. this.onBeforeRenderObservable.add(func);
  32326. return this;
  32327. };
  32328. /**
  32329. * Disposes a previously registered javascript function called before the rendering.
  32330. * This function is passed the current mesh.
  32331. * Returns the Mesh.
  32332. */
  32333. Mesh.prototype.unregisterBeforeRender = function (func) {
  32334. this.onBeforeRenderObservable.removeCallback(func);
  32335. return this;
  32336. };
  32337. /**
  32338. * Registers for this mesh a javascript function called just after the rendering is complete.
  32339. * This function is passed the current mesh.
  32340. * Returns the Mesh.
  32341. */
  32342. Mesh.prototype.registerAfterRender = function (func) {
  32343. this.onAfterRenderObservable.add(func);
  32344. return this;
  32345. };
  32346. /**
  32347. * Disposes a previously registered javascript function called after the rendering.
  32348. * This function is passed the current mesh.
  32349. * Return the Mesh.
  32350. */
  32351. Mesh.prototype.unregisterAfterRender = function (func) {
  32352. this.onAfterRenderObservable.removeCallback(func);
  32353. return this;
  32354. };
  32355. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32356. var scene = this.getScene();
  32357. this._batchCache.mustReturn = false;
  32358. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32359. this._batchCache.visibleInstances[subMeshId] = null;
  32360. if (this._visibleInstances) {
  32361. var currentRenderId = scene.getRenderId();
  32362. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32363. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32364. var selfRenderId = this._renderId;
  32365. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32366. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32367. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32368. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32369. }
  32370. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32371. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32372. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32373. this._batchCache.mustReturn = true;
  32374. return this._batchCache;
  32375. }
  32376. if (currentRenderId !== selfRenderId) {
  32377. this._batchCache.renderSelf[subMeshId] = false;
  32378. }
  32379. }
  32380. this._renderIdForInstances[subMeshId] = currentRenderId;
  32381. }
  32382. return this._batchCache;
  32383. };
  32384. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32385. var visibleInstances = batch.visibleInstances[subMesh._id];
  32386. if (!visibleInstances) {
  32387. return this;
  32388. }
  32389. var matricesCount = visibleInstances.length + 1;
  32390. var bufferSize = matricesCount * 16 * 4;
  32391. var currentInstancesBufferSize = this._instancesBufferSize;
  32392. var instancesBuffer = this._instancesBuffer;
  32393. while (this._instancesBufferSize < bufferSize) {
  32394. this._instancesBufferSize *= 2;
  32395. }
  32396. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32397. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32398. }
  32399. var offset = 0;
  32400. var instancesCount = 0;
  32401. var world = this.getWorldMatrix();
  32402. if (batch.renderSelf[subMesh._id]) {
  32403. world.copyToArray(this._instancesData, offset);
  32404. offset += 16;
  32405. instancesCount++;
  32406. }
  32407. if (visibleInstances) {
  32408. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32409. var instance = visibleInstances[instanceIndex];
  32410. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32411. offset += 16;
  32412. instancesCount++;
  32413. }
  32414. }
  32415. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32416. if (instancesBuffer) {
  32417. instancesBuffer.dispose();
  32418. }
  32419. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32420. this._instancesBuffer = instancesBuffer;
  32421. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32422. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32423. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32424. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32425. }
  32426. else {
  32427. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32428. }
  32429. this._bind(subMesh, effect, fillMode);
  32430. this._draw(subMesh, fillMode, instancesCount);
  32431. engine.unbindInstanceAttributes();
  32432. return this;
  32433. };
  32434. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32435. var scene = this.getScene();
  32436. var engine = scene.getEngine();
  32437. if (hardwareInstancedRendering) {
  32438. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32439. }
  32440. else {
  32441. if (batch.renderSelf[subMesh._id]) {
  32442. // Draw
  32443. if (onBeforeDraw) {
  32444. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32445. }
  32446. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32447. }
  32448. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32449. if (visibleInstancesForSubMesh) {
  32450. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32451. var instance = visibleInstancesForSubMesh[instanceIndex];
  32452. // World
  32453. var world = instance.getWorldMatrix();
  32454. if (onBeforeDraw) {
  32455. onBeforeDraw(true, world, effectiveMaterial);
  32456. }
  32457. // Draw
  32458. this._draw(subMesh, fillMode);
  32459. }
  32460. }
  32461. }
  32462. return this;
  32463. };
  32464. /**
  32465. * Triggers the draw call for the mesh.
  32466. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32467. * Returns the Mesh.
  32468. */
  32469. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32470. this._checkOcclusionQuery();
  32471. if (this._isOccluded) {
  32472. return this;
  32473. }
  32474. var scene = this.getScene();
  32475. // Managing instances
  32476. var batch = this._getInstancesRenderList(subMesh._id);
  32477. if (batch.mustReturn) {
  32478. return this;
  32479. }
  32480. // Checking geometry state
  32481. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32482. return this;
  32483. }
  32484. this.onBeforeRenderObservable.notifyObservers(this);
  32485. var engine = scene.getEngine();
  32486. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32487. // Material
  32488. var material = subMesh.getMaterial();
  32489. if (!material) {
  32490. return this;
  32491. }
  32492. this._effectiveMaterial = material;
  32493. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32494. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32495. return this;
  32496. }
  32497. }
  32498. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32499. return this;
  32500. }
  32501. // Alpha mode
  32502. if (enableAlphaMode) {
  32503. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32504. }
  32505. // Outline - step 1
  32506. var savedDepthWrite = engine.getDepthWrite();
  32507. if (this.renderOutline) {
  32508. engine.setDepthWrite(false);
  32509. scene.getOutlineRenderer().render(subMesh, batch);
  32510. engine.setDepthWrite(savedDepthWrite);
  32511. }
  32512. var effect;
  32513. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32514. effect = subMesh.effect;
  32515. }
  32516. else {
  32517. effect = this._effectiveMaterial.getEffect();
  32518. }
  32519. if (!effect) {
  32520. return this;
  32521. }
  32522. var sideOrientation = this.overrideMaterialSideOrientation;
  32523. if (sideOrientation == null) {
  32524. sideOrientation = this._effectiveMaterial.sideOrientation;
  32525. if (this._getWorldMatrixDeterminant() < 0) {
  32526. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32527. }
  32528. }
  32529. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32530. if (this._effectiveMaterial.forceDepthWrite) {
  32531. engine.setDepthWrite(true);
  32532. }
  32533. // Bind
  32534. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32535. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32536. this._bind(subMesh, effect, fillMode);
  32537. }
  32538. var world = this.getWorldMatrix();
  32539. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32540. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32541. }
  32542. else {
  32543. this._effectiveMaterial.bind(world, this);
  32544. }
  32545. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32546. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32547. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32548. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32549. }
  32550. // Draw
  32551. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32552. // Unbind
  32553. this._effectiveMaterial.unbind();
  32554. // Outline - step 2
  32555. if (this.renderOutline && savedDepthWrite) {
  32556. engine.setDepthWrite(true);
  32557. engine.setColorWrite(false);
  32558. scene.getOutlineRenderer().render(subMesh, batch);
  32559. engine.setColorWrite(true);
  32560. }
  32561. // Overlay
  32562. if (this.renderOverlay) {
  32563. var currentMode = engine.getAlphaMode();
  32564. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32565. scene.getOutlineRenderer().render(subMesh, batch, true);
  32566. engine.setAlphaMode(currentMode);
  32567. }
  32568. this.onAfterRenderObservable.notifyObservers(this);
  32569. return this;
  32570. };
  32571. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32572. if (isInstance && effectiveMaterial) {
  32573. effectiveMaterial.bindOnlyWorldMatrix(world);
  32574. }
  32575. };
  32576. /**
  32577. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32578. */
  32579. Mesh.prototype.getEmittedParticleSystems = function () {
  32580. var results = new Array();
  32581. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32582. var particleSystem = this.getScene().particleSystems[index];
  32583. if (particleSystem.emitter === this) {
  32584. results.push(particleSystem);
  32585. }
  32586. }
  32587. return results;
  32588. };
  32589. /**
  32590. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32591. */
  32592. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32593. var results = new Array();
  32594. var descendants = this.getDescendants();
  32595. descendants.push(this);
  32596. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32597. var particleSystem = this.getScene().particleSystems[index];
  32598. var emitter = particleSystem.emitter;
  32599. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32600. results.push(particleSystem);
  32601. }
  32602. }
  32603. return results;
  32604. };
  32605. /**
  32606. * Normalize matrix weights so that all vertices have a total weight set to 1
  32607. */
  32608. Mesh.prototype.cleanMatrixWeights = function () {
  32609. var epsilon = 1e-3;
  32610. var noInfluenceBoneIndex = 0.0;
  32611. if (this.skeleton) {
  32612. noInfluenceBoneIndex = this.skeleton.bones.length;
  32613. }
  32614. else {
  32615. return;
  32616. }
  32617. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32618. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32619. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32620. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32621. var influencers = this.numBoneInfluencers;
  32622. var size = matricesWeights.length;
  32623. for (var i = 0; i < size; i += 4) {
  32624. var weight = 0.0;
  32625. var firstZeroWeight = -1;
  32626. for (var j = 0; j < 4; j++) {
  32627. var w = matricesWeights[i + j];
  32628. weight += w;
  32629. if (w < epsilon && firstZeroWeight < 0) {
  32630. firstZeroWeight = j;
  32631. }
  32632. }
  32633. if (matricesWeightsExtra) {
  32634. for (var j = 0; j < 4; j++) {
  32635. var w = matricesWeightsExtra[i + j];
  32636. weight += w;
  32637. if (w < epsilon && firstZeroWeight < 0) {
  32638. firstZeroWeight = j + 4;
  32639. }
  32640. }
  32641. }
  32642. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32643. firstZeroWeight = influencers - 1;
  32644. }
  32645. if (weight > epsilon) {
  32646. var mweight = 1.0 / weight;
  32647. for (var j = 0; j < 4; j++) {
  32648. matricesWeights[i + j] *= mweight;
  32649. }
  32650. if (matricesWeightsExtra) {
  32651. for (var j = 0; j < 4; j++) {
  32652. matricesWeightsExtra[i + j] *= mweight;
  32653. }
  32654. }
  32655. }
  32656. else {
  32657. if (firstZeroWeight >= 4) {
  32658. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32659. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32660. }
  32661. else {
  32662. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32663. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32664. }
  32665. }
  32666. }
  32667. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32668. if (matricesIndicesExtra) {
  32669. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32670. }
  32671. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32672. if (matricesWeightsExtra) {
  32673. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32674. }
  32675. };
  32676. Mesh.prototype._checkDelayState = function () {
  32677. var scene = this.getScene();
  32678. if (this._geometry) {
  32679. this._geometry.load(scene);
  32680. }
  32681. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32682. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32683. this._queueLoad(scene);
  32684. }
  32685. return this;
  32686. };
  32687. Mesh.prototype._queueLoad = function (scene) {
  32688. var _this = this;
  32689. scene._addPendingData(this);
  32690. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32691. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32692. if (data instanceof ArrayBuffer) {
  32693. _this._delayLoadingFunction(data, _this);
  32694. }
  32695. else {
  32696. _this._delayLoadingFunction(JSON.parse(data), _this);
  32697. }
  32698. _this.instances.forEach(function (instance) {
  32699. instance._syncSubMeshes();
  32700. });
  32701. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32702. scene._removePendingData(_this);
  32703. }, function () { }, scene.database, getBinaryData);
  32704. return this;
  32705. };
  32706. /**
  32707. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32708. */
  32709. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32710. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32711. return false;
  32712. }
  32713. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32714. return false;
  32715. }
  32716. this._checkDelayState();
  32717. return true;
  32718. };
  32719. /**
  32720. * Sets the mesh material by the material or multiMaterial `id` property.
  32721. * The material `id` is a string identifying the material or the multiMaterial.
  32722. * This method returns the Mesh.
  32723. */
  32724. Mesh.prototype.setMaterialByID = function (id) {
  32725. var materials = this.getScene().materials;
  32726. var index;
  32727. for (index = materials.length - 1; index > -1; index--) {
  32728. if (materials[index].id === id) {
  32729. this.material = materials[index];
  32730. return this;
  32731. }
  32732. }
  32733. // Multi
  32734. var multiMaterials = this.getScene().multiMaterials;
  32735. for (index = multiMaterials.length - 1; index > -1; index--) {
  32736. if (multiMaterials[index].id === id) {
  32737. this.material = multiMaterials[index];
  32738. return this;
  32739. }
  32740. }
  32741. return this;
  32742. };
  32743. /**
  32744. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32745. */
  32746. Mesh.prototype.getAnimatables = function () {
  32747. var results = new Array();
  32748. if (this.material) {
  32749. results.push(this.material);
  32750. }
  32751. if (this.skeleton) {
  32752. results.push(this.skeleton);
  32753. }
  32754. return results;
  32755. };
  32756. /**
  32757. * Modifies the mesh geometry according to the passed transformation matrix.
  32758. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32759. * The mesh normals are modified accordingly the same transformation.
  32760. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32761. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32762. * Returns the Mesh.
  32763. */
  32764. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32765. // Position
  32766. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32767. return this;
  32768. }
  32769. var submeshes = this.subMeshes.splice(0);
  32770. this._resetPointsArrayCache();
  32771. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32772. var temp = new Array();
  32773. var index;
  32774. for (index = 0; index < data.length; index += 3) {
  32775. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32776. }
  32777. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32778. // Normals
  32779. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32780. return this;
  32781. }
  32782. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32783. temp = [];
  32784. for (index = 0; index < data.length; index += 3) {
  32785. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32786. }
  32787. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32788. // flip faces?
  32789. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32790. this.flipFaces();
  32791. }
  32792. // Restore submeshes
  32793. this.releaseSubMeshes();
  32794. this.subMeshes = submeshes;
  32795. return this;
  32796. };
  32797. /**
  32798. * Modifies the mesh geometry according to its own current World Matrix.
  32799. * The mesh World Matrix is then reset.
  32800. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32801. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32802. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32803. * Returns the Mesh.
  32804. */
  32805. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32806. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32807. this.scaling.copyFromFloats(1, 1, 1);
  32808. this.position.copyFromFloats(0, 0, 0);
  32809. this.rotation.copyFromFloats(0, 0, 0);
  32810. //only if quaternion is already set
  32811. if (this.rotationQuaternion) {
  32812. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32813. }
  32814. this._worldMatrix = BABYLON.Matrix.Identity();
  32815. return this;
  32816. };
  32817. Object.defineProperty(Mesh.prototype, "_positions", {
  32818. // Cache
  32819. get: function () {
  32820. if (this._geometry) {
  32821. return this._geometry._positions;
  32822. }
  32823. return null;
  32824. },
  32825. enumerable: true,
  32826. configurable: true
  32827. });
  32828. Mesh.prototype._resetPointsArrayCache = function () {
  32829. if (this._geometry) {
  32830. this._geometry._resetPointsArrayCache();
  32831. }
  32832. return this;
  32833. };
  32834. Mesh.prototype._generatePointsArray = function () {
  32835. if (this._geometry) {
  32836. return this._geometry._generatePointsArray();
  32837. }
  32838. return false;
  32839. };
  32840. /**
  32841. * Returns a new Mesh object generated from the current mesh properties.
  32842. * This method must not get confused with createInstance().
  32843. * The parameter `name` is a string, the name given to the new mesh.
  32844. * The optional parameter `newParent` can be any Node object (default `null`).
  32845. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32846. * 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.
  32847. */
  32848. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32849. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32850. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32851. };
  32852. /**
  32853. * Releases resources associated with this mesh.
  32854. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32855. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32856. */
  32857. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32858. var _this = this;
  32859. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32860. this.morphTargetManager = null;
  32861. if (this._geometry) {
  32862. this._geometry.releaseForMesh(this, true);
  32863. }
  32864. // Sources
  32865. var meshes = this.getScene().meshes;
  32866. meshes.forEach(function (abstractMesh) {
  32867. var mesh = abstractMesh;
  32868. if (mesh._source && mesh._source === _this) {
  32869. mesh._source = null;
  32870. }
  32871. });
  32872. this._source = null;
  32873. // Instances
  32874. if (this._instancesBuffer) {
  32875. this._instancesBuffer.dispose();
  32876. this._instancesBuffer = null;
  32877. }
  32878. while (this.instances.length) {
  32879. this.instances[0].dispose();
  32880. }
  32881. // Effect layers.
  32882. var effectLayers = this.getScene().effectLayers;
  32883. for (var i = 0; i < effectLayers.length; i++) {
  32884. var effectLayer = effectLayers[i];
  32885. if (effectLayer) {
  32886. effectLayer._disposeMesh(this);
  32887. }
  32888. }
  32889. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32890. };
  32891. /**
  32892. * Modifies the mesh geometry according to a displacement map.
  32893. * 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.
  32894. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32895. * This method returns nothing.
  32896. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32897. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32898. * 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.
  32899. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32900. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32901. *
  32902. * Returns the Mesh.
  32903. */
  32904. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32905. var _this = this;
  32906. var scene = this.getScene();
  32907. var onload = function (img) {
  32908. // Getting height map data
  32909. var canvas = document.createElement("canvas");
  32910. var context = canvas.getContext("2d");
  32911. var heightMapWidth = img.width;
  32912. var heightMapHeight = img.height;
  32913. canvas.width = heightMapWidth;
  32914. canvas.height = heightMapHeight;
  32915. context.drawImage(img, 0, 0);
  32916. // Create VertexData from map data
  32917. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32918. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32919. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32920. //execute success callback, if set
  32921. if (onSuccess) {
  32922. onSuccess(_this);
  32923. }
  32924. };
  32925. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32926. return this;
  32927. };
  32928. /**
  32929. * Modifies the mesh geometry according to a displacementMap buffer.
  32930. * 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.
  32931. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32932. * This method returns nothing.
  32933. * 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.
  32934. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32935. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32936. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32937. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32938. *
  32939. * Returns the Mesh.
  32940. */
  32941. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32942. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32943. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32944. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32945. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32946. return this;
  32947. }
  32948. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32949. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32950. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32951. var position = BABYLON.Vector3.Zero();
  32952. var normal = BABYLON.Vector3.Zero();
  32953. var uv = BABYLON.Vector2.Zero();
  32954. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32955. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32956. for (var index = 0; index < positions.length; index += 3) {
  32957. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32958. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32959. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32960. // Compute height
  32961. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32962. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32963. var pos = (u + v * heightMapWidth) * 4;
  32964. var r = buffer[pos] / 255.0;
  32965. var g = buffer[pos + 1] / 255.0;
  32966. var b = buffer[pos + 2] / 255.0;
  32967. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32968. normal.normalize();
  32969. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32970. position = position.add(normal);
  32971. position.toArray(positions, index);
  32972. }
  32973. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32974. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32975. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32976. return this;
  32977. };
  32978. /**
  32979. * Modify the mesh to get a flat shading rendering.
  32980. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32981. * This method returns the Mesh.
  32982. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32983. */
  32984. Mesh.prototype.convertToFlatShadedMesh = function () {
  32985. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32986. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32987. var kinds = this.getVerticesDataKinds();
  32988. var vbs = {};
  32989. var data = {};
  32990. var newdata = {};
  32991. var updatableNormals = false;
  32992. var kindIndex;
  32993. var kind;
  32994. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32995. kind = kinds[kindIndex];
  32996. var vertexBuffer = this.getVertexBuffer(kind);
  32997. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32998. updatableNormals = vertexBuffer.isUpdatable();
  32999. kinds.splice(kindIndex, 1);
  33000. kindIndex--;
  33001. continue;
  33002. }
  33003. vbs[kind] = vertexBuffer;
  33004. data[kind] = vbs[kind].getData();
  33005. newdata[kind] = [];
  33006. }
  33007. // Save previous submeshes
  33008. var previousSubmeshes = this.subMeshes.slice(0);
  33009. var indices = this.getIndices();
  33010. var totalIndices = this.getTotalIndices();
  33011. // Generating unique vertices per face
  33012. var index;
  33013. for (index = 0; index < totalIndices; index++) {
  33014. var vertexIndex = indices[index];
  33015. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33016. kind = kinds[kindIndex];
  33017. var stride = vbs[kind].getStrideSize();
  33018. for (var offset = 0; offset < stride; offset++) {
  33019. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33020. }
  33021. }
  33022. }
  33023. // Updating faces & normal
  33024. var normals = [];
  33025. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33026. for (index = 0; index < totalIndices; index += 3) {
  33027. indices[index] = index;
  33028. indices[index + 1] = index + 1;
  33029. indices[index + 2] = index + 2;
  33030. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33031. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33032. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33033. var p1p2 = p1.subtract(p2);
  33034. var p3p2 = p3.subtract(p2);
  33035. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33036. // Store same normals for every vertex
  33037. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33038. normals.push(normal.x);
  33039. normals.push(normal.y);
  33040. normals.push(normal.z);
  33041. }
  33042. }
  33043. this.setIndices(indices);
  33044. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33045. // Updating vertex buffers
  33046. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33047. kind = kinds[kindIndex];
  33048. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33049. }
  33050. // Updating submeshes
  33051. this.releaseSubMeshes();
  33052. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33053. var previousOne = previousSubmeshes[submeshIndex];
  33054. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33055. }
  33056. this.synchronizeInstances();
  33057. return this;
  33058. };
  33059. /**
  33060. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33061. * In other words, more vertices, no more indices and a single bigger VBO.
  33062. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33063. * Returns the Mesh.
  33064. */
  33065. Mesh.prototype.convertToUnIndexedMesh = function () {
  33066. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33067. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33068. var kinds = this.getVerticesDataKinds();
  33069. var vbs = {};
  33070. var data = {};
  33071. var newdata = {};
  33072. var kindIndex;
  33073. var kind;
  33074. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33075. kind = kinds[kindIndex];
  33076. var vertexBuffer = this.getVertexBuffer(kind);
  33077. vbs[kind] = vertexBuffer;
  33078. data[kind] = vbs[kind].getData();
  33079. newdata[kind] = [];
  33080. }
  33081. // Save previous submeshes
  33082. var previousSubmeshes = this.subMeshes.slice(0);
  33083. var indices = this.getIndices();
  33084. var totalIndices = this.getTotalIndices();
  33085. // Generating unique vertices per face
  33086. var index;
  33087. for (index = 0; index < totalIndices; index++) {
  33088. var vertexIndex = indices[index];
  33089. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33090. kind = kinds[kindIndex];
  33091. var stride = vbs[kind].getStrideSize();
  33092. for (var offset = 0; offset < stride; offset++) {
  33093. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33094. }
  33095. }
  33096. }
  33097. // Updating indices
  33098. for (index = 0; index < totalIndices; index += 3) {
  33099. indices[index] = index;
  33100. indices[index + 1] = index + 1;
  33101. indices[index + 2] = index + 2;
  33102. }
  33103. this.setIndices(indices);
  33104. // Updating vertex buffers
  33105. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33106. kind = kinds[kindIndex];
  33107. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33108. }
  33109. // Updating submeshes
  33110. this.releaseSubMeshes();
  33111. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33112. var previousOne = previousSubmeshes[submeshIndex];
  33113. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33114. }
  33115. this._unIndexed = true;
  33116. this.synchronizeInstances();
  33117. return this;
  33118. };
  33119. /**
  33120. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33121. * This method returns the Mesh.
  33122. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33123. */
  33124. Mesh.prototype.flipFaces = function (flipNormals) {
  33125. if (flipNormals === void 0) { flipNormals = false; }
  33126. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33127. var i;
  33128. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33129. for (i = 0; i < vertex_data.normals.length; i++) {
  33130. vertex_data.normals[i] *= -1;
  33131. }
  33132. }
  33133. if (vertex_data.indices) {
  33134. var temp;
  33135. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33136. // reassign indices
  33137. temp = vertex_data.indices[i + 1];
  33138. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33139. vertex_data.indices[i + 2] = temp;
  33140. }
  33141. }
  33142. vertex_data.applyToMesh(this);
  33143. return this;
  33144. };
  33145. // Instances
  33146. /**
  33147. * Creates a new InstancedMesh object from the mesh model.
  33148. * An instance shares the same properties and the same material than its model.
  33149. * Only these properties of each instance can then be set individually :
  33150. * - position
  33151. * - rotation
  33152. * - rotationQuaternion
  33153. * - setPivotMatrix
  33154. * - scaling
  33155. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33156. * Warning : this method is not supported for Line mesh and LineSystem
  33157. */
  33158. Mesh.prototype.createInstance = function (name) {
  33159. return new BABYLON.InstancedMesh(name, this);
  33160. };
  33161. /**
  33162. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33163. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33164. * This method returns the Mesh.
  33165. */
  33166. Mesh.prototype.synchronizeInstances = function () {
  33167. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33168. var instance = this.instances[instanceIndex];
  33169. instance._syncSubMeshes();
  33170. }
  33171. return this;
  33172. };
  33173. /**
  33174. * Simplify the mesh according to the given array of settings.
  33175. * Function will return immediately and will simplify async. It returns the Mesh.
  33176. * @param settings a collection of simplification settings.
  33177. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33178. * @param type the type of simplification to run.
  33179. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33180. */
  33181. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33182. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33183. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33184. this.getScene().simplificationQueue.addTask({
  33185. settings: settings,
  33186. parallelProcessing: parallelProcessing,
  33187. mesh: this,
  33188. simplificationType: simplificationType,
  33189. successCallback: successCallback
  33190. });
  33191. return this;
  33192. };
  33193. /**
  33194. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33195. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33196. * This should be used together with the simplification to avoid disappearing triangles.
  33197. * Returns the Mesh.
  33198. * @param successCallback an optional success callback to be called after the optimization finished.
  33199. */
  33200. Mesh.prototype.optimizeIndices = function (successCallback) {
  33201. var _this = this;
  33202. var indices = this.getIndices();
  33203. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33204. if (!positions || !indices) {
  33205. return this;
  33206. }
  33207. var vectorPositions = new Array();
  33208. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33209. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33210. }
  33211. var dupes = new Array();
  33212. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33213. var realPos = vectorPositions.length - 1 - iteration;
  33214. var testedPosition = vectorPositions[realPos];
  33215. for (var j = 0; j < realPos; ++j) {
  33216. var againstPosition = vectorPositions[j];
  33217. if (testedPosition.equals(againstPosition)) {
  33218. dupes[realPos] = j;
  33219. break;
  33220. }
  33221. }
  33222. }, function () {
  33223. for (var i = 0; i < indices.length; ++i) {
  33224. indices[i] = dupes[indices[i]] || indices[i];
  33225. }
  33226. //indices are now reordered
  33227. var originalSubMeshes = _this.subMeshes.slice(0);
  33228. _this.setIndices(indices);
  33229. _this.subMeshes = originalSubMeshes;
  33230. if (successCallback) {
  33231. successCallback(_this);
  33232. }
  33233. });
  33234. return this;
  33235. };
  33236. Mesh.prototype.serialize = function (serializationObject) {
  33237. serializationObject.name = this.name;
  33238. serializationObject.id = this.id;
  33239. serializationObject.type = this.getClassName();
  33240. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33241. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33242. }
  33243. serializationObject.position = this.position.asArray();
  33244. if (this.rotationQuaternion) {
  33245. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33246. }
  33247. else if (this.rotation) {
  33248. serializationObject.rotation = this.rotation.asArray();
  33249. }
  33250. serializationObject.scaling = this.scaling.asArray();
  33251. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33252. serializationObject.isEnabled = this.isEnabled(false);
  33253. serializationObject.isVisible = this.isVisible;
  33254. serializationObject.infiniteDistance = this.infiniteDistance;
  33255. serializationObject.pickable = this.isPickable;
  33256. serializationObject.receiveShadows = this.receiveShadows;
  33257. serializationObject.billboardMode = this.billboardMode;
  33258. serializationObject.visibility = this.visibility;
  33259. serializationObject.checkCollisions = this.checkCollisions;
  33260. serializationObject.isBlocker = this.isBlocker;
  33261. // Parent
  33262. if (this.parent) {
  33263. serializationObject.parentId = this.parent.id;
  33264. }
  33265. // Geometry
  33266. serializationObject.isUnIndexed = this.isUnIndexed;
  33267. var geometry = this._geometry;
  33268. if (geometry) {
  33269. var geometryId = geometry.id;
  33270. serializationObject.geometryId = geometryId;
  33271. // SubMeshes
  33272. serializationObject.subMeshes = [];
  33273. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33274. var subMesh = this.subMeshes[subIndex];
  33275. serializationObject.subMeshes.push({
  33276. materialIndex: subMesh.materialIndex,
  33277. verticesStart: subMesh.verticesStart,
  33278. verticesCount: subMesh.verticesCount,
  33279. indexStart: subMesh.indexStart,
  33280. indexCount: subMesh.indexCount
  33281. });
  33282. }
  33283. }
  33284. // Material
  33285. if (this.material) {
  33286. serializationObject.materialId = this.material.id;
  33287. }
  33288. else {
  33289. this.material = null;
  33290. }
  33291. // Morph targets
  33292. if (this.morphTargetManager) {
  33293. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33294. }
  33295. // Skeleton
  33296. if (this.skeleton) {
  33297. serializationObject.skeletonId = this.skeleton.id;
  33298. }
  33299. // Physics
  33300. //TODO implement correct serialization for physics impostors.
  33301. var impostor = this.getPhysicsImpostor();
  33302. if (impostor) {
  33303. serializationObject.physicsMass = impostor.getParam("mass");
  33304. serializationObject.physicsFriction = impostor.getParam("friction");
  33305. serializationObject.physicsRestitution = impostor.getParam("mass");
  33306. serializationObject.physicsImpostor = impostor.type;
  33307. }
  33308. // Metadata
  33309. if (this.metadata) {
  33310. serializationObject.metadata = this.metadata;
  33311. }
  33312. // Instances
  33313. serializationObject.instances = [];
  33314. for (var index = 0; index < this.instances.length; index++) {
  33315. var instance = this.instances[index];
  33316. var serializationInstance = {
  33317. name: instance.name,
  33318. id: instance.id,
  33319. position: instance.position.asArray(),
  33320. scaling: instance.scaling.asArray()
  33321. };
  33322. if (instance.rotationQuaternion) {
  33323. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33324. }
  33325. else if (instance.rotation) {
  33326. serializationInstance.rotation = instance.rotation.asArray();
  33327. }
  33328. serializationObject.instances.push(serializationInstance);
  33329. // Animations
  33330. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33331. serializationInstance.ranges = instance.serializeAnimationRanges();
  33332. }
  33333. //
  33334. // Animations
  33335. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33336. serializationObject.ranges = this.serializeAnimationRanges();
  33337. // Layer mask
  33338. serializationObject.layerMask = this.layerMask;
  33339. // Alpha
  33340. serializationObject.alphaIndex = this.alphaIndex;
  33341. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33342. // Overlay
  33343. serializationObject.overlayAlpha = this.overlayAlpha;
  33344. serializationObject.overlayColor = this.overlayColor.asArray();
  33345. serializationObject.renderOverlay = this.renderOverlay;
  33346. // Fog
  33347. serializationObject.applyFog = this.applyFog;
  33348. // Action Manager
  33349. if (this.actionManager) {
  33350. serializationObject.actions = this.actionManager.serialize(this.name);
  33351. }
  33352. };
  33353. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33354. if (!this.geometry) {
  33355. return;
  33356. }
  33357. this._markSubMeshesAsAttributesDirty();
  33358. var morphTargetManager = this._morphTargetManager;
  33359. if (morphTargetManager && morphTargetManager.vertexCount) {
  33360. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33361. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33362. this.morphTargetManager = null;
  33363. return;
  33364. }
  33365. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33366. var morphTarget = morphTargetManager.getActiveTarget(index);
  33367. var positions = morphTarget.getPositions();
  33368. if (!positions) {
  33369. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33370. return;
  33371. }
  33372. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33373. var normals = morphTarget.getNormals();
  33374. if (normals) {
  33375. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33376. }
  33377. var tangents = morphTarget.getTangents();
  33378. if (tangents) {
  33379. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33380. }
  33381. }
  33382. }
  33383. else {
  33384. var index = 0;
  33385. // Positions
  33386. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33387. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33388. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33389. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33390. }
  33391. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33392. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33393. }
  33394. index++;
  33395. }
  33396. }
  33397. };
  33398. // Statics
  33399. /**
  33400. * Returns a new Mesh object parsed from the source provided.
  33401. * The parameter `parsedMesh` is the source.
  33402. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33403. */
  33404. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33405. var mesh;
  33406. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33407. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33408. }
  33409. else {
  33410. mesh = new Mesh(parsedMesh.name, scene);
  33411. }
  33412. mesh.id = parsedMesh.id;
  33413. if (BABYLON.Tags) {
  33414. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33415. }
  33416. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33417. if (parsedMesh.metadata !== undefined) {
  33418. mesh.metadata = parsedMesh.metadata;
  33419. }
  33420. if (parsedMesh.rotationQuaternion) {
  33421. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33422. }
  33423. else if (parsedMesh.rotation) {
  33424. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33425. }
  33426. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33427. if (parsedMesh.localMatrix) {
  33428. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33429. }
  33430. else if (parsedMesh.pivotMatrix) {
  33431. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33432. }
  33433. mesh.setEnabled(parsedMesh.isEnabled);
  33434. mesh.isVisible = parsedMesh.isVisible;
  33435. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33436. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33437. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33438. if (parsedMesh.applyFog !== undefined) {
  33439. mesh.applyFog = parsedMesh.applyFog;
  33440. }
  33441. if (parsedMesh.pickable !== undefined) {
  33442. mesh.isPickable = parsedMesh.pickable;
  33443. }
  33444. if (parsedMesh.alphaIndex !== undefined) {
  33445. mesh.alphaIndex = parsedMesh.alphaIndex;
  33446. }
  33447. mesh.receiveShadows = parsedMesh.receiveShadows;
  33448. mesh.billboardMode = parsedMesh.billboardMode;
  33449. if (parsedMesh.visibility !== undefined) {
  33450. mesh.visibility = parsedMesh.visibility;
  33451. }
  33452. mesh.checkCollisions = parsedMesh.checkCollisions;
  33453. if (parsedMesh.isBlocker !== undefined) {
  33454. mesh.isBlocker = parsedMesh.isBlocker;
  33455. }
  33456. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33457. // freezeWorldMatrix
  33458. if (parsedMesh.freezeWorldMatrix) {
  33459. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33460. }
  33461. // Parent
  33462. if (parsedMesh.parentId) {
  33463. mesh._waitingParentId = parsedMesh.parentId;
  33464. }
  33465. // Actions
  33466. if (parsedMesh.actions !== undefined) {
  33467. mesh._waitingActions = parsedMesh.actions;
  33468. }
  33469. // Overlay
  33470. if (parsedMesh.overlayAlpha !== undefined) {
  33471. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33472. }
  33473. if (parsedMesh.overlayColor !== undefined) {
  33474. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33475. }
  33476. if (parsedMesh.renderOverlay !== undefined) {
  33477. mesh.renderOverlay = parsedMesh.renderOverlay;
  33478. }
  33479. // Geometry
  33480. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33481. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33482. if (parsedMesh.delayLoadingFile) {
  33483. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33484. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33485. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33486. if (parsedMesh._binaryInfo) {
  33487. mesh._binaryInfo = parsedMesh._binaryInfo;
  33488. }
  33489. mesh._delayInfo = [];
  33490. if (parsedMesh.hasUVs) {
  33491. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33492. }
  33493. if (parsedMesh.hasUVs2) {
  33494. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33495. }
  33496. if (parsedMesh.hasUVs3) {
  33497. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33498. }
  33499. if (parsedMesh.hasUVs4) {
  33500. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33501. }
  33502. if (parsedMesh.hasUVs5) {
  33503. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33504. }
  33505. if (parsedMesh.hasUVs6) {
  33506. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33507. }
  33508. if (parsedMesh.hasColors) {
  33509. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33510. }
  33511. if (parsedMesh.hasMatricesIndices) {
  33512. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33513. }
  33514. if (parsedMesh.hasMatricesWeights) {
  33515. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33516. }
  33517. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33518. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33519. mesh._checkDelayState();
  33520. }
  33521. }
  33522. else {
  33523. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33524. }
  33525. // Material
  33526. if (parsedMesh.materialId) {
  33527. mesh.setMaterialByID(parsedMesh.materialId);
  33528. }
  33529. else {
  33530. mesh.material = null;
  33531. }
  33532. // Morph targets
  33533. if (parsedMesh.morphTargetManagerId > -1) {
  33534. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33535. }
  33536. // Skeleton
  33537. if (parsedMesh.skeletonId > -1) {
  33538. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33539. if (parsedMesh.numBoneInfluencers) {
  33540. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33541. }
  33542. }
  33543. // Animations
  33544. if (parsedMesh.animations) {
  33545. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33546. var parsedAnimation = parsedMesh.animations[animationIndex];
  33547. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33548. }
  33549. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33550. }
  33551. if (parsedMesh.autoAnimate) {
  33552. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33553. }
  33554. // Layer Mask
  33555. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33556. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33557. }
  33558. else {
  33559. mesh.layerMask = 0x0FFFFFFF;
  33560. }
  33561. // Physics
  33562. if (parsedMesh.physicsImpostor) {
  33563. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33564. mass: parsedMesh.physicsMass,
  33565. friction: parsedMesh.physicsFriction,
  33566. restitution: parsedMesh.physicsRestitution
  33567. }, scene);
  33568. }
  33569. // Instances
  33570. if (parsedMesh.instances) {
  33571. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33572. var parsedInstance = parsedMesh.instances[index];
  33573. var instance = mesh.createInstance(parsedInstance.name);
  33574. if (parsedInstance.id) {
  33575. instance.id = parsedInstance.id;
  33576. }
  33577. if (BABYLON.Tags) {
  33578. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33579. }
  33580. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33581. if (parsedInstance.parentId) {
  33582. instance._waitingParentId = parsedInstance.parentId;
  33583. }
  33584. if (parsedInstance.rotationQuaternion) {
  33585. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33586. }
  33587. else if (parsedInstance.rotation) {
  33588. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33589. }
  33590. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33591. instance.checkCollisions = mesh.checkCollisions;
  33592. if (parsedMesh.animations) {
  33593. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33594. parsedAnimation = parsedMesh.animations[animationIndex];
  33595. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33596. }
  33597. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33598. }
  33599. }
  33600. }
  33601. return mesh;
  33602. };
  33603. /**
  33604. * Creates a ribbon mesh.
  33605. * Please consider using the same method from the MeshBuilder class instead.
  33606. * 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.
  33607. *
  33608. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33609. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33610. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33611. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33612. * 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.
  33613. * 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.
  33614. * 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
  33615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33616. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33618. */
  33619. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33620. if (closeArray === void 0) { closeArray = false; }
  33621. if (updatable === void 0) { updatable = false; }
  33622. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33623. pathArray: pathArray,
  33624. closeArray: closeArray,
  33625. closePath: closePath,
  33626. offset: offset,
  33627. updatable: updatable,
  33628. sideOrientation: sideOrientation,
  33629. instance: instance
  33630. }, scene);
  33631. };
  33632. /**
  33633. * Creates a plane polygonal mesh. By default, this is a disc.
  33634. * Please consider using the same method from the MeshBuilder class instead.
  33635. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33636. * 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.
  33637. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33638. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33640. */
  33641. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33642. if (scene === void 0) { scene = null; }
  33643. var options = {
  33644. radius: radius,
  33645. tessellation: tessellation,
  33646. sideOrientation: sideOrientation,
  33647. updatable: updatable
  33648. };
  33649. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33650. };
  33651. /**
  33652. * Creates a box mesh.
  33653. * Please consider using the same method from the MeshBuilder class instead.
  33654. * The parameter `size` sets the size (float) of each box side (default 1).
  33655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33656. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33658. */
  33659. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33660. if (scene === void 0) { scene = null; }
  33661. var options = {
  33662. size: size,
  33663. sideOrientation: sideOrientation,
  33664. updatable: updatable
  33665. };
  33666. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33667. };
  33668. /**
  33669. * Creates a sphere mesh.
  33670. * Please consider using the same method from the MeshBuilder class instead.
  33671. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33672. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33673. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33674. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33676. */
  33677. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33678. var options = {
  33679. segments: segments,
  33680. diameterX: diameter,
  33681. diameterY: diameter,
  33682. diameterZ: diameter,
  33683. sideOrientation: sideOrientation,
  33684. updatable: updatable
  33685. };
  33686. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33687. };
  33688. /**
  33689. * Creates a cylinder or a cone mesh.
  33690. * Please consider using the same method from the MeshBuilder class instead.
  33691. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33692. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33693. * 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.
  33694. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33695. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33697. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33699. */
  33700. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33701. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33702. if (scene !== undefined) {
  33703. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33704. updatable = scene;
  33705. }
  33706. scene = subdivisions;
  33707. subdivisions = 1;
  33708. }
  33709. var options = {
  33710. height: height,
  33711. diameterTop: diameterTop,
  33712. diameterBottom: diameterBottom,
  33713. tessellation: tessellation,
  33714. subdivisions: subdivisions,
  33715. sideOrientation: sideOrientation,
  33716. updatable: updatable
  33717. };
  33718. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33719. };
  33720. // Torus (Code from SharpDX.org)
  33721. /**
  33722. * Creates a torus mesh.
  33723. * Please consider using the same method from the MeshBuilder class instead.
  33724. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33725. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33726. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33728. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33730. */
  33731. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33732. var options = {
  33733. diameter: diameter,
  33734. thickness: thickness,
  33735. tessellation: tessellation,
  33736. sideOrientation: sideOrientation,
  33737. updatable: updatable
  33738. };
  33739. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33740. };
  33741. /**
  33742. * Creates a torus knot mesh.
  33743. * Please consider using the same method from the MeshBuilder class instead.
  33744. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33745. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33746. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33747. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33749. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33751. */
  33752. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33753. var options = {
  33754. radius: radius,
  33755. tube: tube,
  33756. radialSegments: radialSegments,
  33757. tubularSegments: tubularSegments,
  33758. p: p,
  33759. q: q,
  33760. sideOrientation: sideOrientation,
  33761. updatable: updatable
  33762. };
  33763. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33764. };
  33765. /**
  33766. * Creates a line mesh.
  33767. * Please consider using the same method from the MeshBuilder class instead.
  33768. * 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.
  33769. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33770. * The parameter `points` is an array successive Vector3.
  33771. * 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
  33772. * When updating an instance, remember that only point positions can change, not the number of points.
  33773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33774. */
  33775. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33776. if (scene === void 0) { scene = null; }
  33777. if (updatable === void 0) { updatable = false; }
  33778. if (instance === void 0) { instance = null; }
  33779. var options = {
  33780. points: points,
  33781. updatable: updatable,
  33782. instance: instance
  33783. };
  33784. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33785. };
  33786. /**
  33787. * Creates a dashed line mesh.
  33788. * Please consider using the same method from the MeshBuilder class instead.
  33789. * 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.
  33790. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33791. * The parameter `points` is an array successive Vector3.
  33792. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33793. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33794. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33795. * 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
  33796. * When updating an instance, remember that only point positions can change, not the number of points.
  33797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33798. */
  33799. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33800. if (scene === void 0) { scene = null; }
  33801. var options = {
  33802. points: points,
  33803. dashSize: dashSize,
  33804. gapSize: gapSize,
  33805. dashNb: dashNb,
  33806. updatable: updatable,
  33807. instance: instance
  33808. };
  33809. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33810. };
  33811. /**
  33812. * Creates a polygon mesh.
  33813. * Please consider using the same method from the MeshBuilder class instead.
  33814. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33815. * 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.
  33816. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33818. * Remember you can only change the shape positions, not their number when updating a polygon.
  33819. */
  33820. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33821. var options = {
  33822. shape: shape,
  33823. holes: holes,
  33824. updatable: updatable,
  33825. sideOrientation: sideOrientation
  33826. };
  33827. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33828. };
  33829. /**
  33830. * Creates an extruded polygon mesh, with depth in the Y direction.
  33831. * Please consider using the same method from the MeshBuilder class instead.
  33832. */
  33833. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33834. var options = {
  33835. shape: shape,
  33836. holes: holes,
  33837. depth: depth,
  33838. updatable: updatable,
  33839. sideOrientation: sideOrientation
  33840. };
  33841. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33842. };
  33843. /**
  33844. * Creates an extruded shape mesh.
  33845. * 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.
  33846. * Please consider using the same method from the MeshBuilder class instead.
  33847. *
  33848. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33849. * 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
  33850. * extruded along the Z axis.
  33851. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33852. * 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.
  33853. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33854. * 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
  33855. * 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
  33856. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33858. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33860. */
  33861. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33862. if (scene === void 0) { scene = null; }
  33863. var options = {
  33864. shape: shape,
  33865. path: path,
  33866. scale: scale,
  33867. rotation: rotation,
  33868. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33869. sideOrientation: sideOrientation,
  33870. instance: instance,
  33871. updatable: updatable
  33872. };
  33873. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33874. };
  33875. /**
  33876. * Creates an custom extruded shape mesh.
  33877. * 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.
  33878. * Please consider using the same method from the MeshBuilder class instead.
  33879. *
  33880. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33881. * 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
  33882. * extruded along the Z axis.
  33883. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33884. * 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
  33885. * and the distance of this point from the begining of the path :
  33886. * ```javascript
  33887. * var rotationFunction = function(i, distance) {
  33888. * // do things
  33889. * return rotationValue; }
  33890. * ```
  33891. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33892. * 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
  33893. * and the distance of this point from the begining of the path :
  33894. * ```javascript
  33895. * var scaleFunction = function(i, distance) {
  33896. * // do things
  33897. * return scaleValue;}
  33898. * ```
  33899. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33900. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33901. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33902. * 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
  33903. * 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
  33904. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33906. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33908. */
  33909. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33910. var options = {
  33911. shape: shape,
  33912. path: path,
  33913. scaleFunction: scaleFunction,
  33914. rotationFunction: rotationFunction,
  33915. ribbonCloseArray: ribbonCloseArray,
  33916. ribbonClosePath: ribbonClosePath,
  33917. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33918. sideOrientation: sideOrientation,
  33919. instance: instance,
  33920. updatable: updatable
  33921. };
  33922. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33923. };
  33924. /**
  33925. * Creates lathe mesh.
  33926. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33927. * Please consider using the same method from the MeshBuilder class instead.
  33928. * 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
  33929. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33930. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33931. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33933. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33935. */
  33936. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33937. var options = {
  33938. shape: shape,
  33939. radius: radius,
  33940. tessellation: tessellation,
  33941. sideOrientation: sideOrientation,
  33942. updatable: updatable
  33943. };
  33944. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33945. };
  33946. /**
  33947. * Creates a plane mesh.
  33948. * Please consider using the same method from the MeshBuilder class instead.
  33949. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33951. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33953. */
  33954. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33955. var options = {
  33956. size: size,
  33957. width: size,
  33958. height: size,
  33959. sideOrientation: sideOrientation,
  33960. updatable: updatable
  33961. };
  33962. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33963. };
  33964. /**
  33965. * Creates a ground mesh.
  33966. * Please consider using the same method from the MeshBuilder class instead.
  33967. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33968. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33970. */
  33971. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33972. var options = {
  33973. width: width,
  33974. height: height,
  33975. subdivisions: subdivisions,
  33976. updatable: updatable
  33977. };
  33978. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33979. };
  33980. /**
  33981. * Creates a tiled ground mesh.
  33982. * Please consider using the same method from the MeshBuilder class instead.
  33983. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33984. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33985. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33986. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33987. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33988. * numbers of subdivisions on the ground width and height of each tile.
  33989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33990. */
  33991. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33992. var options = {
  33993. xmin: xmin,
  33994. zmin: zmin,
  33995. xmax: xmax,
  33996. zmax: zmax,
  33997. subdivisions: subdivisions,
  33998. precision: precision,
  33999. updatable: updatable
  34000. };
  34001. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34002. };
  34003. /**
  34004. * Creates a ground mesh from a height map.
  34005. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34006. * Please consider using the same method from the MeshBuilder class instead.
  34007. * The parameter `url` sets the URL of the height map image resource.
  34008. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34009. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34010. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34011. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34012. * 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).
  34013. * This function is passed the newly built mesh :
  34014. * ```javascript
  34015. * function(mesh) { // do things
  34016. * return; }
  34017. * ```
  34018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34019. */
  34020. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34021. var options = {
  34022. width: width,
  34023. height: height,
  34024. subdivisions: subdivisions,
  34025. minHeight: minHeight,
  34026. maxHeight: maxHeight,
  34027. updatable: updatable,
  34028. onReady: onReady
  34029. };
  34030. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34031. };
  34032. /**
  34033. * Creates a tube mesh.
  34034. * 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.
  34035. * Please consider using the same method from the MeshBuilder class instead.
  34036. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34037. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34038. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34039. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34040. * 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.
  34041. * It must return a radius value (positive float) :
  34042. * ```javascript
  34043. * var radiusFunction = function(i, distance) {
  34044. * // do things
  34045. * return radius; }
  34046. * ```
  34047. * 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
  34048. * 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
  34049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34050. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34052. */
  34053. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34054. var options = {
  34055. path: path,
  34056. radius: radius,
  34057. tessellation: tessellation,
  34058. radiusFunction: radiusFunction,
  34059. arc: 1,
  34060. cap: cap,
  34061. updatable: updatable,
  34062. sideOrientation: sideOrientation,
  34063. instance: instance
  34064. };
  34065. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34066. };
  34067. /**
  34068. * Creates a polyhedron mesh.
  34069. * Please consider using the same method from the MeshBuilder class instead.
  34070. * 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
  34071. * to choose the wanted type.
  34072. * The parameter `size` (positive float, default 1) sets the polygon size.
  34073. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34074. * 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`.
  34075. * 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
  34076. * 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)`).
  34077. * 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
  34078. * 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.
  34079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34080. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34082. */
  34083. Mesh.CreatePolyhedron = function (name, options, scene) {
  34084. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34085. };
  34086. /**
  34087. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34088. * Please consider using the same method from the MeshBuilder class instead.
  34089. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34090. * 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`).
  34091. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34092. * 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.
  34093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34094. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34096. */
  34097. Mesh.CreateIcoSphere = function (name, options, scene) {
  34098. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34099. };
  34100. /**
  34101. * Creates a decal mesh.
  34102. * Please consider using the same method from the MeshBuilder class instead.
  34103. * 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.
  34104. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34105. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34106. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34107. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34108. */
  34109. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34110. var options = {
  34111. position: position,
  34112. normal: normal,
  34113. size: size,
  34114. angle: angle
  34115. };
  34116. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34117. };
  34118. // Skeletons
  34119. /**
  34120. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34121. */
  34122. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34123. if (!this._sourcePositions) {
  34124. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34125. if (!source) {
  34126. return this._sourcePositions;
  34127. }
  34128. this._sourcePositions = new Float32Array(source);
  34129. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34130. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34131. }
  34132. }
  34133. return this._sourcePositions;
  34134. };
  34135. /**
  34136. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34137. */
  34138. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34139. if (!this._sourceNormals) {
  34140. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34141. if (!source) {
  34142. return this._sourceNormals;
  34143. }
  34144. this._sourceNormals = new Float32Array(source);
  34145. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34146. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34147. }
  34148. }
  34149. return this._sourceNormals;
  34150. };
  34151. /**
  34152. * Updates the vertex buffer by applying transformation from the bones.
  34153. * Returns the Mesh.
  34154. *
  34155. * @param {skeleton} skeleton to apply
  34156. */
  34157. Mesh.prototype.applySkeleton = function (skeleton) {
  34158. if (!this.geometry) {
  34159. return this;
  34160. }
  34161. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34162. return this;
  34163. }
  34164. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34165. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34166. return this;
  34167. }
  34168. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34169. return this;
  34170. }
  34171. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34172. return this;
  34173. }
  34174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34175. return this;
  34176. }
  34177. if (!this._sourcePositions) {
  34178. var submeshes = this.subMeshes.slice();
  34179. this.setPositionsForCPUSkinning();
  34180. this.subMeshes = submeshes;
  34181. }
  34182. if (!this._sourceNormals) {
  34183. this.setNormalsForCPUSkinning();
  34184. }
  34185. // positionsData checks for not being Float32Array will only pass at most once
  34186. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34187. if (!positionsData) {
  34188. return this;
  34189. }
  34190. if (!(positionsData instanceof Float32Array)) {
  34191. positionsData = new Float32Array(positionsData);
  34192. }
  34193. // normalsData checks for not being Float32Array will only pass at most once
  34194. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34195. if (!normalsData) {
  34196. return this;
  34197. }
  34198. if (!(normalsData instanceof Float32Array)) {
  34199. normalsData = new Float32Array(normalsData);
  34200. }
  34201. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34202. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34203. if (!matricesWeightsData || !matricesIndicesData) {
  34204. return this;
  34205. }
  34206. var needExtras = this.numBoneInfluencers > 4;
  34207. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34208. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34209. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34210. var tempVector3 = BABYLON.Vector3.Zero();
  34211. var finalMatrix = new BABYLON.Matrix();
  34212. var tempMatrix = new BABYLON.Matrix();
  34213. var matWeightIdx = 0;
  34214. var inf;
  34215. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34216. var weight;
  34217. for (inf = 0; inf < 4; inf++) {
  34218. weight = matricesWeightsData[matWeightIdx + inf];
  34219. if (weight > 0) {
  34220. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34221. finalMatrix.addToSelf(tempMatrix);
  34222. }
  34223. else
  34224. break;
  34225. }
  34226. if (needExtras) {
  34227. for (inf = 0; inf < 4; inf++) {
  34228. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34229. if (weight > 0) {
  34230. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34231. finalMatrix.addToSelf(tempMatrix);
  34232. }
  34233. else
  34234. break;
  34235. }
  34236. }
  34237. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34238. tempVector3.toArray(positionsData, index);
  34239. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34240. tempVector3.toArray(normalsData, index);
  34241. finalMatrix.reset();
  34242. }
  34243. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34244. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34245. return this;
  34246. };
  34247. // Tools
  34248. /**
  34249. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34250. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34251. */
  34252. Mesh.MinMax = function (meshes) {
  34253. var minVector = null;
  34254. var maxVector = null;
  34255. meshes.forEach(function (mesh, index, array) {
  34256. var boundingInfo = mesh.getBoundingInfo();
  34257. var boundingBox = boundingInfo.boundingBox;
  34258. if (!minVector || !maxVector) {
  34259. minVector = boundingBox.minimumWorld;
  34260. maxVector = boundingBox.maximumWorld;
  34261. }
  34262. else {
  34263. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34264. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34265. }
  34266. });
  34267. if (!minVector || !maxVector) {
  34268. return {
  34269. min: BABYLON.Vector3.Zero(),
  34270. max: BABYLON.Vector3.Zero()
  34271. };
  34272. }
  34273. return {
  34274. min: minVector,
  34275. max: maxVector
  34276. };
  34277. };
  34278. /**
  34279. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34280. */
  34281. Mesh.Center = function (meshesOrMinMaxVector) {
  34282. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34283. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34284. };
  34285. /**
  34286. * Merge the array of meshes into a single mesh for performance reasons.
  34287. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34288. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34289. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34290. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34291. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34292. */
  34293. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34294. if (disposeSource === void 0) { disposeSource = true; }
  34295. var index;
  34296. if (!allow32BitsIndices) {
  34297. var totalVertices = 0;
  34298. // Counting vertices
  34299. for (index = 0; index < meshes.length; index++) {
  34300. if (meshes[index]) {
  34301. totalVertices += meshes[index].getTotalVertices();
  34302. if (totalVertices > 65536) {
  34303. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34304. return null;
  34305. }
  34306. }
  34307. }
  34308. }
  34309. // Merge
  34310. var vertexData = null;
  34311. var otherVertexData;
  34312. var indiceArray = new Array();
  34313. var source = null;
  34314. for (index = 0; index < meshes.length; index++) {
  34315. if (meshes[index]) {
  34316. meshes[index].computeWorldMatrix(true);
  34317. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34318. otherVertexData.transform(meshes[index].getWorldMatrix());
  34319. if (vertexData) {
  34320. vertexData.merge(otherVertexData);
  34321. }
  34322. else {
  34323. vertexData = otherVertexData;
  34324. source = meshes[index];
  34325. }
  34326. if (subdivideWithSubMeshes) {
  34327. indiceArray.push(meshes[index].getTotalIndices());
  34328. }
  34329. }
  34330. }
  34331. source = source;
  34332. if (!meshSubclass) {
  34333. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34334. }
  34335. vertexData.applyToMesh(meshSubclass);
  34336. // Setting properties
  34337. meshSubclass.material = source.material;
  34338. meshSubclass.checkCollisions = source.checkCollisions;
  34339. // Cleaning
  34340. if (disposeSource) {
  34341. for (index = 0; index < meshes.length; index++) {
  34342. if (meshes[index]) {
  34343. meshes[index].dispose();
  34344. }
  34345. }
  34346. }
  34347. // Subdivide
  34348. if (subdivideWithSubMeshes) {
  34349. //-- removal of global submesh
  34350. meshSubclass.releaseSubMeshes();
  34351. index = 0;
  34352. var offset = 0;
  34353. //-- apply subdivision according to index table
  34354. while (index < indiceArray.length) {
  34355. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34356. offset += indiceArray[index];
  34357. index++;
  34358. }
  34359. }
  34360. return meshSubclass;
  34361. };
  34362. // Consts
  34363. Mesh._FRONTSIDE = 0;
  34364. Mesh._BACKSIDE = 1;
  34365. Mesh._DOUBLESIDE = 2;
  34366. Mesh._DEFAULTSIDE = 0;
  34367. Mesh._NO_CAP = 0;
  34368. Mesh._CAP_START = 1;
  34369. Mesh._CAP_END = 2;
  34370. Mesh._CAP_ALL = 3;
  34371. return Mesh;
  34372. }(BABYLON.AbstractMesh));
  34373. BABYLON.Mesh = Mesh;
  34374. })(BABYLON || (BABYLON = {}));
  34375. //# sourceMappingURL=babylon.mesh.js.map
  34376. var BABYLON;
  34377. (function (BABYLON) {
  34378. var BaseSubMesh = /** @class */ (function () {
  34379. function BaseSubMesh() {
  34380. }
  34381. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34382. get: function () {
  34383. return this._materialEffect;
  34384. },
  34385. enumerable: true,
  34386. configurable: true
  34387. });
  34388. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34389. if (defines === void 0) { defines = null; }
  34390. if (this._materialEffect === effect) {
  34391. if (!effect) {
  34392. this._materialDefines = null;
  34393. }
  34394. return;
  34395. }
  34396. this._materialDefines = defines;
  34397. this._materialEffect = effect;
  34398. };
  34399. return BaseSubMesh;
  34400. }());
  34401. BABYLON.BaseSubMesh = BaseSubMesh;
  34402. var SubMesh = /** @class */ (function (_super) {
  34403. __extends(SubMesh, _super);
  34404. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34405. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34406. var _this = _super.call(this) || this;
  34407. _this.materialIndex = materialIndex;
  34408. _this.verticesStart = verticesStart;
  34409. _this.verticesCount = verticesCount;
  34410. _this.indexStart = indexStart;
  34411. _this.indexCount = indexCount;
  34412. _this._renderId = 0;
  34413. _this._mesh = mesh;
  34414. _this._renderingMesh = renderingMesh || mesh;
  34415. mesh.subMeshes.push(_this);
  34416. _this._trianglePlanes = [];
  34417. _this._id = mesh.subMeshes.length - 1;
  34418. if (createBoundingBox) {
  34419. _this.refreshBoundingInfo();
  34420. mesh.computeWorldMatrix(true);
  34421. }
  34422. return _this;
  34423. }
  34424. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34425. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34426. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34427. };
  34428. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34429. get: function () {
  34430. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34431. },
  34432. enumerable: true,
  34433. configurable: true
  34434. });
  34435. /**
  34436. * Returns the submesh BoudingInfo object.
  34437. */
  34438. SubMesh.prototype.getBoundingInfo = function () {
  34439. if (this.IsGlobal) {
  34440. return this._mesh.getBoundingInfo();
  34441. }
  34442. return this._boundingInfo;
  34443. };
  34444. /**
  34445. * Sets the submesh BoundingInfo.
  34446. * Return the SubMesh.
  34447. */
  34448. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34449. this._boundingInfo = boundingInfo;
  34450. return this;
  34451. };
  34452. /**
  34453. * Returns the mesh of the current submesh.
  34454. */
  34455. SubMesh.prototype.getMesh = function () {
  34456. return this._mesh;
  34457. };
  34458. /**
  34459. * Returns the rendering mesh of the submesh.
  34460. */
  34461. SubMesh.prototype.getRenderingMesh = function () {
  34462. return this._renderingMesh;
  34463. };
  34464. /**
  34465. * Returns the submesh material.
  34466. */
  34467. SubMesh.prototype.getMaterial = function () {
  34468. var rootMaterial = this._renderingMesh.material;
  34469. if (rootMaterial === null || rootMaterial === undefined) {
  34470. return this._mesh.getScene().defaultMaterial;
  34471. }
  34472. else if (rootMaterial.getSubMaterial) {
  34473. var multiMaterial = rootMaterial;
  34474. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34475. if (this._currentMaterial !== effectiveMaterial) {
  34476. this._currentMaterial = effectiveMaterial;
  34477. this._materialDefines = null;
  34478. }
  34479. return effectiveMaterial;
  34480. }
  34481. return rootMaterial;
  34482. };
  34483. // Methods
  34484. /**
  34485. * Sets a new updated BoundingInfo object to the submesh.
  34486. * Returns the SubMesh.
  34487. */
  34488. SubMesh.prototype.refreshBoundingInfo = function () {
  34489. this._lastColliderWorldVertices = null;
  34490. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34491. return this;
  34492. }
  34493. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34494. if (!data) {
  34495. this._boundingInfo = this._mesh.getBoundingInfo();
  34496. return this;
  34497. }
  34498. var indices = this._renderingMesh.getIndices();
  34499. var extend;
  34500. //is this the only submesh?
  34501. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34502. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34503. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34504. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34505. }
  34506. else {
  34507. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34508. }
  34509. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34510. return this;
  34511. };
  34512. SubMesh.prototype._checkCollision = function (collider) {
  34513. var boundingInfo = this.getBoundingInfo();
  34514. return boundingInfo._checkCollision(collider);
  34515. };
  34516. /**
  34517. * Updates the submesh BoundingInfo.
  34518. * Returns the Submesh.
  34519. */
  34520. SubMesh.prototype.updateBoundingInfo = function (world) {
  34521. var boundingInfo = this.getBoundingInfo();
  34522. if (!boundingInfo) {
  34523. this.refreshBoundingInfo();
  34524. boundingInfo = this.getBoundingInfo();
  34525. }
  34526. boundingInfo.update(world);
  34527. return this;
  34528. };
  34529. /**
  34530. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34531. * Boolean returned.
  34532. */
  34533. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34534. var boundingInfo = this.getBoundingInfo();
  34535. if (!boundingInfo) {
  34536. return false;
  34537. }
  34538. return boundingInfo.isInFrustum(frustumPlanes);
  34539. };
  34540. /**
  34541. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34542. * Boolean returned.
  34543. */
  34544. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34545. var boundingInfo = this.getBoundingInfo();
  34546. if (!boundingInfo) {
  34547. return false;
  34548. }
  34549. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34550. };
  34551. /**
  34552. * Renders the submesh.
  34553. * Returns it.
  34554. */
  34555. SubMesh.prototype.render = function (enableAlphaMode) {
  34556. this._renderingMesh.render(this, enableAlphaMode);
  34557. return this;
  34558. };
  34559. /**
  34560. * Returns a new Index Buffer.
  34561. * Type returned : WebGLBuffer.
  34562. */
  34563. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34564. if (!this._linesIndexBuffer) {
  34565. var linesIndices = [];
  34566. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34567. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34568. }
  34569. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34570. this.linesIndexCount = linesIndices.length;
  34571. }
  34572. return this._linesIndexBuffer;
  34573. };
  34574. /**
  34575. * True is the passed Ray intersects the submesh bounding box.
  34576. * Boolean returned.
  34577. */
  34578. SubMesh.prototype.canIntersects = function (ray) {
  34579. var boundingInfo = this.getBoundingInfo();
  34580. if (!boundingInfo) {
  34581. return false;
  34582. }
  34583. return ray.intersectsBox(boundingInfo.boundingBox);
  34584. };
  34585. /**
  34586. * Returns an object IntersectionInfo.
  34587. */
  34588. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34589. var intersectInfo = null;
  34590. var material = this.getMaterial();
  34591. if (!material) {
  34592. return null;
  34593. }
  34594. switch (material.fillMode) {
  34595. case BABYLON.Material.PointListDrawMode:
  34596. case BABYLON.Material.LineListDrawMode:
  34597. case BABYLON.Material.LineLoopDrawMode:
  34598. case BABYLON.Material.LineStripDrawMode:
  34599. case BABYLON.Material.TriangleFanDrawMode:
  34600. case BABYLON.Material.TriangleStripDrawMode:
  34601. return null;
  34602. }
  34603. // LineMesh first as it's also a Mesh...
  34604. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34605. var lineMesh = this._mesh;
  34606. // Line test
  34607. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34608. var p0 = positions[indices[index]];
  34609. var p1 = positions[indices[index + 1]];
  34610. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34611. if (length < 0) {
  34612. continue;
  34613. }
  34614. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34615. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34616. if (fastCheck) {
  34617. break;
  34618. }
  34619. }
  34620. }
  34621. }
  34622. else {
  34623. // Triangles test
  34624. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34625. var p0 = positions[indices[index]];
  34626. var p1 = positions[indices[index + 1]];
  34627. var p2 = positions[indices[index + 2]];
  34628. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34629. if (currentIntersectInfo) {
  34630. if (currentIntersectInfo.distance < 0) {
  34631. continue;
  34632. }
  34633. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34634. intersectInfo = currentIntersectInfo;
  34635. intersectInfo.faceId = index / 3;
  34636. if (fastCheck) {
  34637. break;
  34638. }
  34639. }
  34640. }
  34641. }
  34642. }
  34643. return intersectInfo;
  34644. };
  34645. SubMesh.prototype._rebuild = function () {
  34646. if (this._linesIndexBuffer) {
  34647. this._linesIndexBuffer = null;
  34648. }
  34649. };
  34650. // Clone
  34651. /**
  34652. * Creates a new Submesh from the passed Mesh.
  34653. */
  34654. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34655. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34656. if (!this.IsGlobal) {
  34657. var boundingInfo = this.getBoundingInfo();
  34658. if (!boundingInfo) {
  34659. return result;
  34660. }
  34661. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34662. }
  34663. return result;
  34664. };
  34665. // Dispose
  34666. /**
  34667. * Disposes the Submesh.
  34668. * Returns nothing.
  34669. */
  34670. SubMesh.prototype.dispose = function () {
  34671. if (this._linesIndexBuffer) {
  34672. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34673. this._linesIndexBuffer = null;
  34674. }
  34675. // Remove from mesh
  34676. var index = this._mesh.subMeshes.indexOf(this);
  34677. this._mesh.subMeshes.splice(index, 1);
  34678. };
  34679. // Statics
  34680. /**
  34681. * Creates a new Submesh from the passed parameters :
  34682. * - materialIndex (integer) : the index of the main mesh material.
  34683. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34684. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34685. * - mesh (Mesh) : the main mesh to create the submesh from.
  34686. * - renderingMesh (optional Mesh) : rendering mesh.
  34687. */
  34688. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34689. var minVertexIndex = Number.MAX_VALUE;
  34690. var maxVertexIndex = -Number.MAX_VALUE;
  34691. renderingMesh = (renderingMesh || mesh);
  34692. var indices = renderingMesh.getIndices();
  34693. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34694. var vertexIndex = indices[index];
  34695. if (vertexIndex < minVertexIndex)
  34696. minVertexIndex = vertexIndex;
  34697. if (vertexIndex > maxVertexIndex)
  34698. maxVertexIndex = vertexIndex;
  34699. }
  34700. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34701. };
  34702. return SubMesh;
  34703. }(BaseSubMesh));
  34704. BABYLON.SubMesh = SubMesh;
  34705. })(BABYLON || (BABYLON = {}));
  34706. //# sourceMappingURL=babylon.subMesh.js.map
  34707. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34708. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34709. s = arguments[i];
  34710. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34711. t[p] = s[p];
  34712. }
  34713. return t;
  34714. };
  34715. var BABYLON;
  34716. (function (BABYLON) {
  34717. /**
  34718. * Manages the defines for the Material
  34719. */
  34720. var MaterialDefines = /** @class */ (function () {
  34721. function MaterialDefines() {
  34722. this._isDirty = true;
  34723. /** @hidden */
  34724. this._areLightsDirty = true;
  34725. /** @hidden */
  34726. this._areAttributesDirty = true;
  34727. /** @hidden */
  34728. this._areTexturesDirty = true;
  34729. /** @hidden */
  34730. this._areFresnelDirty = true;
  34731. /** @hidden */
  34732. this._areMiscDirty = true;
  34733. /** @hidden */
  34734. this._areImageProcessingDirty = true;
  34735. /** @hidden */
  34736. this._normals = false;
  34737. /** @hidden */
  34738. this._uvs = false;
  34739. /** @hidden */
  34740. this._needNormals = false;
  34741. /** @hidden */
  34742. this._needUVs = false;
  34743. }
  34744. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34745. /**
  34746. * Specifies if the material needs to be re-calculated
  34747. */
  34748. get: function () {
  34749. return this._isDirty;
  34750. },
  34751. enumerable: true,
  34752. configurable: true
  34753. });
  34754. /**
  34755. * Marks the material to indicate that it has been re-calculated
  34756. */
  34757. MaterialDefines.prototype.markAsProcessed = function () {
  34758. this._isDirty = false;
  34759. this._areAttributesDirty = false;
  34760. this._areTexturesDirty = false;
  34761. this._areFresnelDirty = false;
  34762. this._areLightsDirty = false;
  34763. this._areMiscDirty = false;
  34764. this._areImageProcessingDirty = false;
  34765. };
  34766. /**
  34767. * Marks the material to indicate that it needs to be re-calculated
  34768. */
  34769. MaterialDefines.prototype.markAsUnprocessed = function () {
  34770. this._isDirty = true;
  34771. };
  34772. /**
  34773. * Marks the material to indicate all of its defines need to be re-calculated
  34774. */
  34775. MaterialDefines.prototype.markAllAsDirty = function () {
  34776. this._areTexturesDirty = true;
  34777. this._areAttributesDirty = true;
  34778. this._areLightsDirty = true;
  34779. this._areFresnelDirty = true;
  34780. this._areMiscDirty = true;
  34781. this._areImageProcessingDirty = true;
  34782. this._isDirty = true;
  34783. };
  34784. /**
  34785. * Marks the material to indicate that image processing needs to be re-calculated
  34786. */
  34787. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34788. this._areImageProcessingDirty = true;
  34789. this._isDirty = true;
  34790. };
  34791. /**
  34792. * Marks the material to indicate the lights need to be re-calculated
  34793. */
  34794. MaterialDefines.prototype.markAsLightDirty = function () {
  34795. this._areLightsDirty = true;
  34796. this._isDirty = true;
  34797. };
  34798. /**
  34799. * Marks the attribute state as changed
  34800. */
  34801. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34802. this._areAttributesDirty = true;
  34803. this._isDirty = true;
  34804. };
  34805. /**
  34806. * Marks the texture state as changed
  34807. */
  34808. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34809. this._areTexturesDirty = true;
  34810. this._isDirty = true;
  34811. };
  34812. /**
  34813. * Marks the fresnel state as changed
  34814. */
  34815. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34816. this._areFresnelDirty = true;
  34817. this._isDirty = true;
  34818. };
  34819. /**
  34820. * Marks the misc state as changed
  34821. */
  34822. MaterialDefines.prototype.markAsMiscDirty = function () {
  34823. this._areMiscDirty = true;
  34824. this._isDirty = true;
  34825. };
  34826. /**
  34827. * Rebuilds the material defines
  34828. */
  34829. MaterialDefines.prototype.rebuild = function () {
  34830. if (this._keys) {
  34831. delete this._keys;
  34832. }
  34833. this._keys = [];
  34834. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34835. var key = _a[_i];
  34836. if (key[0] === "_") {
  34837. continue;
  34838. }
  34839. this._keys.push(key);
  34840. }
  34841. };
  34842. /**
  34843. * Specifies if two material defines are equal
  34844. * @param other - A material define instance to compare to
  34845. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34846. */
  34847. MaterialDefines.prototype.isEqual = function (other) {
  34848. if (this._keys.length !== other._keys.length) {
  34849. return false;
  34850. }
  34851. for (var index = 0; index < this._keys.length; index++) {
  34852. var prop = this._keys[index];
  34853. if (this[prop] !== other[prop]) {
  34854. return false;
  34855. }
  34856. }
  34857. return true;
  34858. };
  34859. /**
  34860. * Clones this instance's defines to another instance
  34861. * @param other - material defines to clone values to
  34862. */
  34863. MaterialDefines.prototype.cloneTo = function (other) {
  34864. if (this._keys.length !== other._keys.length) {
  34865. other._keys = this._keys.slice(0);
  34866. }
  34867. for (var index = 0; index < this._keys.length; index++) {
  34868. var prop = this._keys[index];
  34869. other[prop] = this[prop];
  34870. }
  34871. };
  34872. /**
  34873. * Resets the material define values
  34874. */
  34875. MaterialDefines.prototype.reset = function () {
  34876. for (var index = 0; index < this._keys.length; index++) {
  34877. var prop = this._keys[index];
  34878. var type = typeof this[prop];
  34879. switch (type) {
  34880. case "number":
  34881. this[prop] = 0;
  34882. break;
  34883. case "string":
  34884. this[prop] = "";
  34885. break;
  34886. default:
  34887. this[prop] = false;
  34888. break;
  34889. }
  34890. }
  34891. };
  34892. /**
  34893. * Converts the material define values to a string
  34894. * @returns - String of material define information
  34895. */
  34896. MaterialDefines.prototype.toString = function () {
  34897. var result = "";
  34898. for (var index = 0; index < this._keys.length; index++) {
  34899. var prop = this._keys[index];
  34900. var value = this[prop];
  34901. var type = typeof value;
  34902. switch (type) {
  34903. case "number":
  34904. case "string":
  34905. result += "#define " + prop + " " + value + "\n";
  34906. break;
  34907. default:
  34908. if (value) {
  34909. result += "#define " + prop + "\n";
  34910. }
  34911. break;
  34912. }
  34913. }
  34914. return result;
  34915. };
  34916. return MaterialDefines;
  34917. }());
  34918. BABYLON.MaterialDefines = MaterialDefines;
  34919. /**
  34920. * Base class for the main features of a material in Babylon.js
  34921. */
  34922. var Material = /** @class */ (function () {
  34923. /**
  34924. * Creates a material instance
  34925. * @param name defines the name of the material
  34926. * @param scene defines the scene to reference
  34927. * @param doNotAdd specifies if the material should be added to the scene
  34928. */
  34929. function Material(name, scene, doNotAdd) {
  34930. /**
  34931. * Specifies if the ready state should be checked on each call
  34932. */
  34933. this.checkReadyOnEveryCall = false;
  34934. /**
  34935. * Specifies if the ready state should be checked once
  34936. */
  34937. this.checkReadyOnlyOnce = false;
  34938. /**
  34939. * The state of the material
  34940. */
  34941. this.state = "";
  34942. /**
  34943. * The alpha value of the material
  34944. */
  34945. this._alpha = 1.0;
  34946. /**
  34947. * Specifies if back face culling is enabled
  34948. */
  34949. this._backFaceCulling = true;
  34950. /**
  34951. * Specifies if the material should be serialized
  34952. */
  34953. this.doNotSerialize = false;
  34954. /**
  34955. * Specifies if the effect should be stored on sub meshes
  34956. */
  34957. this.storeEffectOnSubMeshes = false;
  34958. /**
  34959. * An event triggered when the material is disposed
  34960. */
  34961. this.onDisposeObservable = new BABYLON.Observable();
  34962. /**
  34963. * An event triggered when the material is bound
  34964. */
  34965. this.onBindObservable = new BABYLON.Observable();
  34966. /**
  34967. * An event triggered when the material is unbound
  34968. */
  34969. this.onUnBindObservable = new BABYLON.Observable();
  34970. /**
  34971. * Stores the value of the alpha mode
  34972. */
  34973. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34974. /**
  34975. * Stores the state of the need depth pre-pass value
  34976. */
  34977. this._needDepthPrePass = false;
  34978. /**
  34979. * Specifies if depth writing should be disabled
  34980. */
  34981. this.disableDepthWrite = false;
  34982. /**
  34983. * Specifies if depth writing should be forced
  34984. */
  34985. this.forceDepthWrite = false;
  34986. /**
  34987. * Specifies if there should be a separate pass for culling
  34988. */
  34989. this.separateCullingPass = false;
  34990. /**
  34991. * Stores the state specifing if fog should be enabled
  34992. */
  34993. this._fogEnabled = true;
  34994. /**
  34995. * Stores the size of points
  34996. */
  34997. this.pointSize = 1.0;
  34998. /**
  34999. * Stores the z offset value
  35000. */
  35001. this.zOffset = 0;
  35002. /**
  35003. * Specifies if the material was previously ready
  35004. */
  35005. this._wasPreviouslyReady = false;
  35006. /**
  35007. * Stores the fill mode state
  35008. */
  35009. this._fillMode = Material.TriangleFillMode;
  35010. this.name = name;
  35011. this.id = name || BABYLON.Tools.RandomId();
  35012. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35013. this.uniqueId = this._scene.getUniqueId();
  35014. if (this._scene.useRightHandedSystem) {
  35015. this.sideOrientation = Material.ClockWiseSideOrientation;
  35016. }
  35017. else {
  35018. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35019. }
  35020. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35021. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35022. if (!doNotAdd) {
  35023. this._scene.materials.push(this);
  35024. }
  35025. }
  35026. Object.defineProperty(Material, "TriangleFillMode", {
  35027. /**
  35028. * Returns the triangle fill mode
  35029. */
  35030. get: function () {
  35031. return Material._TriangleFillMode;
  35032. },
  35033. enumerable: true,
  35034. configurable: true
  35035. });
  35036. Object.defineProperty(Material, "WireFrameFillMode", {
  35037. /**
  35038. * Returns the wireframe mode
  35039. */
  35040. get: function () {
  35041. return Material._WireFrameFillMode;
  35042. },
  35043. enumerable: true,
  35044. configurable: true
  35045. });
  35046. Object.defineProperty(Material, "PointFillMode", {
  35047. /**
  35048. * Returns the point fill mode
  35049. */
  35050. get: function () {
  35051. return Material._PointFillMode;
  35052. },
  35053. enumerable: true,
  35054. configurable: true
  35055. });
  35056. Object.defineProperty(Material, "PointListDrawMode", {
  35057. /**
  35058. * Returns the point list draw mode
  35059. */
  35060. get: function () {
  35061. return Material._PointListDrawMode;
  35062. },
  35063. enumerable: true,
  35064. configurable: true
  35065. });
  35066. Object.defineProperty(Material, "LineListDrawMode", {
  35067. /**
  35068. * Returns the line list draw mode
  35069. */
  35070. get: function () {
  35071. return Material._LineListDrawMode;
  35072. },
  35073. enumerable: true,
  35074. configurable: true
  35075. });
  35076. Object.defineProperty(Material, "LineLoopDrawMode", {
  35077. /**
  35078. * Returns the line loop draw mode
  35079. */
  35080. get: function () {
  35081. return Material._LineLoopDrawMode;
  35082. },
  35083. enumerable: true,
  35084. configurable: true
  35085. });
  35086. Object.defineProperty(Material, "LineStripDrawMode", {
  35087. /**
  35088. * Returns the line strip draw mode
  35089. */
  35090. get: function () {
  35091. return Material._LineStripDrawMode;
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35097. /**
  35098. * Returns the triangle strip draw mode
  35099. */
  35100. get: function () {
  35101. return Material._TriangleStripDrawMode;
  35102. },
  35103. enumerable: true,
  35104. configurable: true
  35105. });
  35106. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35107. /**
  35108. * Returns the triangle fan draw mode
  35109. */
  35110. get: function () {
  35111. return Material._TriangleFanDrawMode;
  35112. },
  35113. enumerable: true,
  35114. configurable: true
  35115. });
  35116. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35117. /**
  35118. * Returns the clock-wise side orientation
  35119. */
  35120. get: function () {
  35121. return Material._ClockWiseSideOrientation;
  35122. },
  35123. enumerable: true,
  35124. configurable: true
  35125. });
  35126. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35127. /**
  35128. * Returns the counter clock-wise side orientation
  35129. */
  35130. get: function () {
  35131. return Material._CounterClockWiseSideOrientation;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(Material, "TextureDirtyFlag", {
  35137. /**
  35138. * Returns the dirty texture flag value
  35139. */
  35140. get: function () {
  35141. return Material._TextureDirtyFlag;
  35142. },
  35143. enumerable: true,
  35144. configurable: true
  35145. });
  35146. Object.defineProperty(Material, "LightDirtyFlag", {
  35147. /**
  35148. * Returns the dirty light flag value
  35149. */
  35150. get: function () {
  35151. return Material._LightDirtyFlag;
  35152. },
  35153. enumerable: true,
  35154. configurable: true
  35155. });
  35156. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35157. /**
  35158. * Returns the dirty fresnel flag value
  35159. */
  35160. get: function () {
  35161. return Material._FresnelDirtyFlag;
  35162. },
  35163. enumerable: true,
  35164. configurable: true
  35165. });
  35166. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35167. /**
  35168. * Returns the dirty attributes flag value
  35169. */
  35170. get: function () {
  35171. return Material._AttributesDirtyFlag;
  35172. },
  35173. enumerable: true,
  35174. configurable: true
  35175. });
  35176. Object.defineProperty(Material, "MiscDirtyFlag", {
  35177. /**
  35178. * Returns the dirty misc flag value
  35179. */
  35180. get: function () {
  35181. return Material._MiscDirtyFlag;
  35182. },
  35183. enumerable: true,
  35184. configurable: true
  35185. });
  35186. Object.defineProperty(Material.prototype, "alpha", {
  35187. /**
  35188. * Gets the alpha value of the material
  35189. */
  35190. get: function () {
  35191. return this._alpha;
  35192. },
  35193. /**
  35194. * Sets the alpha value of the material
  35195. */
  35196. set: function (value) {
  35197. if (this._alpha === value) {
  35198. return;
  35199. }
  35200. this._alpha = value;
  35201. this.markAsDirty(Material.MiscDirtyFlag);
  35202. },
  35203. enumerable: true,
  35204. configurable: true
  35205. });
  35206. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35207. /**
  35208. * Gets the back-face culling state
  35209. */
  35210. get: function () {
  35211. return this._backFaceCulling;
  35212. },
  35213. /**
  35214. * Sets the back-face culling state
  35215. */
  35216. set: function (value) {
  35217. if (this._backFaceCulling === value) {
  35218. return;
  35219. }
  35220. this._backFaceCulling = value;
  35221. this.markAsDirty(Material.TextureDirtyFlag);
  35222. },
  35223. enumerable: true,
  35224. configurable: true
  35225. });
  35226. Object.defineProperty(Material.prototype, "onDispose", {
  35227. /**
  35228. * Called during a dispose event
  35229. */
  35230. set: function (callback) {
  35231. if (this._onDisposeObserver) {
  35232. this.onDisposeObservable.remove(this._onDisposeObserver);
  35233. }
  35234. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35235. },
  35236. enumerable: true,
  35237. configurable: true
  35238. });
  35239. Object.defineProperty(Material.prototype, "onBind", {
  35240. /**
  35241. * Called during a bind event
  35242. */
  35243. set: function (callback) {
  35244. if (this._onBindObserver) {
  35245. this.onBindObservable.remove(this._onBindObserver);
  35246. }
  35247. this._onBindObserver = this.onBindObservable.add(callback);
  35248. },
  35249. enumerable: true,
  35250. configurable: true
  35251. });
  35252. Object.defineProperty(Material.prototype, "alphaMode", {
  35253. /**
  35254. * Gets the value of the alpha mode
  35255. */
  35256. get: function () {
  35257. return this._alphaMode;
  35258. },
  35259. /**
  35260. * Sets the value of the alpha mode.
  35261. *
  35262. * | Value | Type | Description |
  35263. * | --- | --- | --- |
  35264. * | 0 | ALPHA_DISABLE | |
  35265. * | 1 | ALPHA_ADD | |
  35266. * | 2 | ALPHA_COMBINE | |
  35267. * | 3 | ALPHA_SUBTRACT | |
  35268. * | 4 | ALPHA_MULTIPLY | |
  35269. * | 5 | ALPHA_MAXIMIZED | |
  35270. * | 6 | ALPHA_ONEONE | |
  35271. * | 7 | ALPHA_PREMULTIPLIED | |
  35272. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35273. * | 9 | ALPHA_INTERPOLATE | |
  35274. * | 10 | ALPHA_SCREENMODE | |
  35275. *
  35276. */
  35277. set: function (value) {
  35278. if (this._alphaMode === value) {
  35279. return;
  35280. }
  35281. this._alphaMode = value;
  35282. this.markAsDirty(Material.TextureDirtyFlag);
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35288. /**
  35289. * Gets the depth pre-pass value
  35290. */
  35291. get: function () {
  35292. return this._needDepthPrePass;
  35293. },
  35294. /**
  35295. * Sets the need depth pre-pass value
  35296. */
  35297. set: function (value) {
  35298. if (this._needDepthPrePass === value) {
  35299. return;
  35300. }
  35301. this._needDepthPrePass = value;
  35302. if (this._needDepthPrePass) {
  35303. this.checkReadyOnEveryCall = true;
  35304. }
  35305. },
  35306. enumerable: true,
  35307. configurable: true
  35308. });
  35309. Object.defineProperty(Material.prototype, "fogEnabled", {
  35310. /**
  35311. * Gets the value of the fog enabled state
  35312. */
  35313. get: function () {
  35314. return this._fogEnabled;
  35315. },
  35316. /**
  35317. * Sets the state for enabling fog
  35318. */
  35319. set: function (value) {
  35320. if (this._fogEnabled === value) {
  35321. return;
  35322. }
  35323. this._fogEnabled = value;
  35324. this.markAsDirty(Material.MiscDirtyFlag);
  35325. },
  35326. enumerable: true,
  35327. configurable: true
  35328. });
  35329. Object.defineProperty(Material.prototype, "wireframe", {
  35330. /**
  35331. * Gets a value specifying if wireframe mode is enabled
  35332. */
  35333. get: function () {
  35334. switch (this._fillMode) {
  35335. case Material.WireFrameFillMode:
  35336. case Material.LineListDrawMode:
  35337. case Material.LineLoopDrawMode:
  35338. case Material.LineStripDrawMode:
  35339. return true;
  35340. }
  35341. return this._scene.forceWireframe;
  35342. },
  35343. /**
  35344. * Sets the state of wireframe mode
  35345. */
  35346. set: function (value) {
  35347. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35348. },
  35349. enumerable: true,
  35350. configurable: true
  35351. });
  35352. Object.defineProperty(Material.prototype, "pointsCloud", {
  35353. /**
  35354. * Gets the value specifying if point clouds are enabled
  35355. */
  35356. get: function () {
  35357. switch (this._fillMode) {
  35358. case Material.PointFillMode:
  35359. case Material.PointListDrawMode:
  35360. return true;
  35361. }
  35362. return this._scene.forcePointsCloud;
  35363. },
  35364. /**
  35365. * Sets the state of point cloud mode
  35366. */
  35367. set: function (value) {
  35368. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35369. },
  35370. enumerable: true,
  35371. configurable: true
  35372. });
  35373. Object.defineProperty(Material.prototype, "fillMode", {
  35374. /**
  35375. * Gets the material fill mode
  35376. */
  35377. get: function () {
  35378. return this._fillMode;
  35379. },
  35380. /**
  35381. * Sets the material fill mode
  35382. */
  35383. set: function (value) {
  35384. if (this._fillMode === value) {
  35385. return;
  35386. }
  35387. this._fillMode = value;
  35388. this.markAsDirty(Material.MiscDirtyFlag);
  35389. },
  35390. enumerable: true,
  35391. configurable: true
  35392. });
  35393. /**
  35394. * Returns a string representation of the current material
  35395. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35396. * @returns a string with material information
  35397. */
  35398. Material.prototype.toString = function (fullDetails) {
  35399. var ret = "Name: " + this.name;
  35400. if (fullDetails) {
  35401. }
  35402. return ret;
  35403. };
  35404. /**
  35405. * Gets the class name of the material
  35406. * @returns a string with the class name of the material
  35407. */
  35408. Material.prototype.getClassName = function () {
  35409. return "Material";
  35410. };
  35411. Object.defineProperty(Material.prototype, "isFrozen", {
  35412. /**
  35413. * Specifies if updates for the material been locked
  35414. */
  35415. get: function () {
  35416. return this.checkReadyOnlyOnce;
  35417. },
  35418. enumerable: true,
  35419. configurable: true
  35420. });
  35421. /**
  35422. * Locks updates for the material
  35423. */
  35424. Material.prototype.freeze = function () {
  35425. this.checkReadyOnlyOnce = true;
  35426. };
  35427. /**
  35428. * Unlocks updates for the material
  35429. */
  35430. Material.prototype.unfreeze = function () {
  35431. this.checkReadyOnlyOnce = false;
  35432. };
  35433. /**
  35434. * Specifies if the material is ready to be used
  35435. * @param mesh defines the mesh to check
  35436. * @param useInstances specifies if instances should be used
  35437. * @returns a boolean indicating if the material is ready to be used
  35438. */
  35439. Material.prototype.isReady = function (mesh, useInstances) {
  35440. return true;
  35441. };
  35442. /**
  35443. * Specifies that the submesh is ready to be used
  35444. * @param mesh defines the mesh to check
  35445. * @param subMesh defines which submesh to check
  35446. * @param useInstances specifies that instances should be used
  35447. * @returns a boolean indicating that the submesh is ready or not
  35448. */
  35449. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35450. return false;
  35451. };
  35452. /**
  35453. * Returns the material effect
  35454. * @returns the effect associated with the material
  35455. */
  35456. Material.prototype.getEffect = function () {
  35457. return this._effect;
  35458. };
  35459. /**
  35460. * Returns the current scene
  35461. * @returns a Scene
  35462. */
  35463. Material.prototype.getScene = function () {
  35464. return this._scene;
  35465. };
  35466. /**
  35467. * Specifies if the material will require alpha blending
  35468. * @returns a boolean specifying if alpha blending is needed
  35469. */
  35470. Material.prototype.needAlphaBlending = function () {
  35471. return (this.alpha < 1.0);
  35472. };
  35473. /**
  35474. * Specifies if the mesh will require alpha blending
  35475. * @param mesh defines the mesh to check
  35476. * @returns a boolean specifying if alpha blending is needed for the mesh
  35477. */
  35478. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35479. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35480. };
  35481. /**
  35482. * Specifies if this material should be rendered in alpha test mode
  35483. * @returns a boolean specifying if an alpha test is needed.
  35484. */
  35485. Material.prototype.needAlphaTesting = function () {
  35486. return false;
  35487. };
  35488. /**
  35489. * Gets the texture used for the alpha test
  35490. * @returns the texture to use for alpha testing
  35491. */
  35492. Material.prototype.getAlphaTestTexture = function () {
  35493. return null;
  35494. };
  35495. /**
  35496. * Marks the material to indicate that it needs to be re-calculated
  35497. */
  35498. Material.prototype.markDirty = function () {
  35499. this._wasPreviouslyReady = false;
  35500. };
  35501. /** @hidden */
  35502. Material.prototype._preBind = function (effect, overrideOrientation) {
  35503. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35504. var engine = this._scene.getEngine();
  35505. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35506. var reverse = orientation === Material.ClockWiseSideOrientation;
  35507. engine.enableEffect(effect ? effect : this._effect);
  35508. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35509. return reverse;
  35510. };
  35511. /**
  35512. * Binds the material to the mesh
  35513. * @param world defines the world transformation matrix
  35514. * @param mesh defines the mesh to bind the material to
  35515. */
  35516. Material.prototype.bind = function (world, mesh) {
  35517. };
  35518. /**
  35519. * Binds the submesh to the material
  35520. * @param world defines the world transformation matrix
  35521. * @param mesh defines the mesh containing the submesh
  35522. * @param subMesh defines the submesh to bind the material to
  35523. */
  35524. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35525. };
  35526. /**
  35527. * Binds the world matrix to the material
  35528. * @param world defines the world transformation matrix
  35529. */
  35530. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35531. };
  35532. /**
  35533. * Binds the scene's uniform buffer to the effect.
  35534. * @param effect defines the effect to bind to the scene uniform buffer
  35535. * @param sceneUbo defines the uniform buffer storing scene data
  35536. */
  35537. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35538. sceneUbo.bindToEffect(effect, "Scene");
  35539. };
  35540. /**
  35541. * Binds the view matrix to the effect
  35542. * @param effect defines the effect to bind the view matrix to
  35543. */
  35544. Material.prototype.bindView = function (effect) {
  35545. if (!this._useUBO) {
  35546. effect.setMatrix("view", this.getScene().getViewMatrix());
  35547. }
  35548. else {
  35549. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35550. }
  35551. };
  35552. /**
  35553. * Binds the view projection matrix to the effect
  35554. * @param effect defines the effect to bind the view projection matrix to
  35555. */
  35556. Material.prototype.bindViewProjection = function (effect) {
  35557. if (!this._useUBO) {
  35558. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35559. }
  35560. else {
  35561. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35562. }
  35563. };
  35564. /**
  35565. * Specifies if material alpha testing should be turned on for the mesh
  35566. * @param mesh defines the mesh to check
  35567. */
  35568. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35569. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35570. };
  35571. /**
  35572. * Processes to execute after binding the material to a mesh
  35573. * @param mesh defines the rendered mesh
  35574. */
  35575. Material.prototype._afterBind = function (mesh) {
  35576. this._scene._cachedMaterial = this;
  35577. if (mesh) {
  35578. this._scene._cachedVisibility = mesh.visibility;
  35579. }
  35580. else {
  35581. this._scene._cachedVisibility = 1;
  35582. }
  35583. if (mesh) {
  35584. this.onBindObservable.notifyObservers(mesh);
  35585. }
  35586. if (this.disableDepthWrite) {
  35587. var engine = this._scene.getEngine();
  35588. this._cachedDepthWriteState = engine.getDepthWrite();
  35589. engine.setDepthWrite(false);
  35590. }
  35591. };
  35592. /**
  35593. * Unbinds the material from the mesh
  35594. */
  35595. Material.prototype.unbind = function () {
  35596. this.onUnBindObservable.notifyObservers(this);
  35597. if (this.disableDepthWrite) {
  35598. var engine = this._scene.getEngine();
  35599. engine.setDepthWrite(this._cachedDepthWriteState);
  35600. }
  35601. };
  35602. /**
  35603. * Gets the active textures from the material
  35604. * @returns an array of textures
  35605. */
  35606. Material.prototype.getActiveTextures = function () {
  35607. return [];
  35608. };
  35609. /**
  35610. * Specifies if the material uses a texture
  35611. * @param texture defines the texture to check against the material
  35612. * @returns a boolean specifying if the material uses the texture
  35613. */
  35614. Material.prototype.hasTexture = function (texture) {
  35615. return false;
  35616. };
  35617. /**
  35618. * Makes a duplicate of the material, and gives it a new name
  35619. * @param name defines the new name for the duplicated material
  35620. * @returns the cloned material
  35621. */
  35622. Material.prototype.clone = function (name) {
  35623. return null;
  35624. };
  35625. /**
  35626. * Gets the meshes bound to the material
  35627. * @returns an array of meshes bound to the material
  35628. */
  35629. Material.prototype.getBindedMeshes = function () {
  35630. var result = new Array();
  35631. for (var index = 0; index < this._scene.meshes.length; index++) {
  35632. var mesh = this._scene.meshes[index];
  35633. if (mesh.material === this) {
  35634. result.push(mesh);
  35635. }
  35636. }
  35637. return result;
  35638. };
  35639. /**
  35640. * Force shader compilation
  35641. * @param mesh defines the mesh associated with this material
  35642. * @param onCompiled defines a function to execute once the material is compiled
  35643. * @param options defines the options to configure the compilation
  35644. */
  35645. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35646. var _this = this;
  35647. var localOptions = __assign({ clipPlane: false }, options);
  35648. var subMesh = new BABYLON.BaseSubMesh();
  35649. var scene = this.getScene();
  35650. var checkReady = function () {
  35651. if (!_this._scene || !_this._scene.getEngine()) {
  35652. return;
  35653. }
  35654. if (subMesh._materialDefines) {
  35655. subMesh._materialDefines._renderId = -1;
  35656. }
  35657. var clipPlaneState = scene.clipPlane;
  35658. if (localOptions.clipPlane) {
  35659. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35660. }
  35661. if (_this.storeEffectOnSubMeshes) {
  35662. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35663. if (onCompiled) {
  35664. onCompiled(_this);
  35665. }
  35666. }
  35667. else {
  35668. setTimeout(checkReady, 16);
  35669. }
  35670. }
  35671. else {
  35672. if (_this.isReady(mesh)) {
  35673. if (onCompiled) {
  35674. onCompiled(_this);
  35675. }
  35676. }
  35677. else {
  35678. setTimeout(checkReady, 16);
  35679. }
  35680. }
  35681. if (localOptions.clipPlane) {
  35682. scene.clipPlane = clipPlaneState;
  35683. }
  35684. };
  35685. checkReady();
  35686. };
  35687. /**
  35688. * Force shader compilation
  35689. * @param mesh defines the mesh that will use this material
  35690. * @param options defines additional options for compiling the shaders
  35691. * @returns a promise that resolves when the compilation completes
  35692. */
  35693. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35694. var _this = this;
  35695. return new Promise(function (resolve) {
  35696. _this.forceCompilation(mesh, function () {
  35697. resolve();
  35698. }, options);
  35699. });
  35700. };
  35701. /**
  35702. * Marks a define in the material to indicate that it needs to be re-computed
  35703. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35704. */
  35705. Material.prototype.markAsDirty = function (flag) {
  35706. if (flag & Material.TextureDirtyFlag) {
  35707. this._markAllSubMeshesAsTexturesDirty();
  35708. }
  35709. if (flag & Material.LightDirtyFlag) {
  35710. this._markAllSubMeshesAsLightsDirty();
  35711. }
  35712. if (flag & Material.FresnelDirtyFlag) {
  35713. this._markAllSubMeshesAsFresnelDirty();
  35714. }
  35715. if (flag & Material.AttributesDirtyFlag) {
  35716. this._markAllSubMeshesAsAttributesDirty();
  35717. }
  35718. if (flag & Material.MiscDirtyFlag) {
  35719. this._markAllSubMeshesAsMiscDirty();
  35720. }
  35721. this.getScene().resetCachedMaterial();
  35722. };
  35723. /**
  35724. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35725. * @param func defines a function which checks material defines against the submeshes
  35726. */
  35727. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35728. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35729. var mesh = _a[_i];
  35730. if (!mesh.subMeshes) {
  35731. continue;
  35732. }
  35733. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35734. var subMesh = _c[_b];
  35735. if (subMesh.getMaterial() !== this) {
  35736. continue;
  35737. }
  35738. if (!subMesh._materialDefines) {
  35739. continue;
  35740. }
  35741. func(subMesh._materialDefines);
  35742. }
  35743. }
  35744. };
  35745. /**
  35746. * Indicates that image processing needs to be re-calculated for all submeshes
  35747. */
  35748. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35749. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35750. };
  35751. /**
  35752. * Indicates that textures need to be re-calculated for all submeshes
  35753. */
  35754. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35755. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35756. };
  35757. /**
  35758. * Indicates that fresnel needs to be re-calculated for all submeshes
  35759. */
  35760. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35761. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35762. };
  35763. /**
  35764. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35765. */
  35766. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35767. this._markAllSubMeshesAsDirty(function (defines) {
  35768. defines.markAsFresnelDirty();
  35769. defines.markAsMiscDirty();
  35770. });
  35771. };
  35772. /**
  35773. * Indicates that lights need to be re-calculated for all submeshes
  35774. */
  35775. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35776. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35777. };
  35778. /**
  35779. * Indicates that attributes need to be re-calculated for all submeshes
  35780. */
  35781. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35782. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35783. };
  35784. /**
  35785. * Indicates that misc needs to be re-calculated for all submeshes
  35786. */
  35787. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35788. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35789. };
  35790. /**
  35791. * Indicates that textures and misc need to be re-calculated for all submeshes
  35792. */
  35793. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35794. this._markAllSubMeshesAsDirty(function (defines) {
  35795. defines.markAsTexturesDirty();
  35796. defines.markAsMiscDirty();
  35797. });
  35798. };
  35799. /**
  35800. * Disposes the material
  35801. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35802. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35803. */
  35804. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35805. // Animations
  35806. this.getScene().stopAnimation(this);
  35807. this.getScene().freeProcessedMaterials();
  35808. // Remove from scene
  35809. var index = this._scene.materials.indexOf(this);
  35810. if (index >= 0) {
  35811. this._scene.materials.splice(index, 1);
  35812. }
  35813. // Remove from meshes
  35814. for (index = 0; index < this._scene.meshes.length; index++) {
  35815. var mesh = this._scene.meshes[index];
  35816. if (mesh.material === this) {
  35817. mesh.material = null;
  35818. if (mesh.geometry) {
  35819. var geometry = (mesh.geometry);
  35820. if (this.storeEffectOnSubMeshes) {
  35821. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35822. var subMesh = _a[_i];
  35823. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35824. if (forceDisposeEffect && subMesh._materialEffect) {
  35825. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35826. }
  35827. }
  35828. }
  35829. else {
  35830. geometry._releaseVertexArrayObject(this._effect);
  35831. }
  35832. }
  35833. }
  35834. }
  35835. this._uniformBuffer.dispose();
  35836. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35837. if (forceDisposeEffect && this._effect) {
  35838. if (!this.storeEffectOnSubMeshes) {
  35839. this._scene.getEngine()._releaseEffect(this._effect);
  35840. }
  35841. this._effect = null;
  35842. }
  35843. // Callback
  35844. this.onDisposeObservable.notifyObservers(this);
  35845. this.onDisposeObservable.clear();
  35846. this.onBindObservable.clear();
  35847. this.onUnBindObservable.clear();
  35848. };
  35849. /**
  35850. * Serializes this material
  35851. * @returns the serialized material object
  35852. */
  35853. Material.prototype.serialize = function () {
  35854. return BABYLON.SerializationHelper.Serialize(this);
  35855. };
  35856. /**
  35857. * Creates a MultiMaterial from parsed MultiMaterial data.
  35858. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35859. * @param scene defines the hosting scene
  35860. * @returns a new MultiMaterial
  35861. */
  35862. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35863. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35864. multiMaterial.id = parsedMultiMaterial.id;
  35865. if (BABYLON.Tags) {
  35866. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35867. }
  35868. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35869. var subMatId = parsedMultiMaterial.materials[matIndex];
  35870. if (subMatId) {
  35871. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35872. }
  35873. else {
  35874. multiMaterial.subMaterials.push(null);
  35875. }
  35876. }
  35877. return multiMaterial;
  35878. };
  35879. /**
  35880. * Creates a material from parsed material data
  35881. * @param parsedMaterial defines parsed material data
  35882. * @param scene defines the hosting scene
  35883. * @param rootUrl defines the root URL to use to load textures
  35884. * @returns a new material
  35885. */
  35886. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35887. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35888. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35889. }
  35890. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35891. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35892. if (!BABYLON.LegacyPBRMaterial) {
  35893. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35894. return;
  35895. }
  35896. }
  35897. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35898. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35899. };
  35900. // Triangle views
  35901. Material._TriangleFillMode = 0;
  35902. Material._WireFrameFillMode = 1;
  35903. Material._PointFillMode = 2;
  35904. // Draw modes
  35905. Material._PointListDrawMode = 3;
  35906. Material._LineListDrawMode = 4;
  35907. Material._LineLoopDrawMode = 5;
  35908. Material._LineStripDrawMode = 6;
  35909. Material._TriangleStripDrawMode = 7;
  35910. Material._TriangleFanDrawMode = 8;
  35911. /**
  35912. * Stores the clock-wise side orientation
  35913. */
  35914. Material._ClockWiseSideOrientation = 0;
  35915. /**
  35916. * Stores the counter clock-wise side orientation
  35917. */
  35918. Material._CounterClockWiseSideOrientation = 1;
  35919. /**
  35920. * The dirty texture flag value
  35921. */
  35922. Material._TextureDirtyFlag = 1;
  35923. /**
  35924. * The dirty light flag value
  35925. */
  35926. Material._LightDirtyFlag = 2;
  35927. /**
  35928. * The dirty fresnel flag value
  35929. */
  35930. Material._FresnelDirtyFlag = 4;
  35931. /**
  35932. * The dirty attribute flag value
  35933. */
  35934. Material._AttributesDirtyFlag = 8;
  35935. /**
  35936. * The dirty misc flag value
  35937. */
  35938. Material._MiscDirtyFlag = 16;
  35939. __decorate([
  35940. BABYLON.serialize()
  35941. ], Material.prototype, "id", void 0);
  35942. __decorate([
  35943. BABYLON.serialize()
  35944. ], Material.prototype, "uniqueId", void 0);
  35945. __decorate([
  35946. BABYLON.serialize()
  35947. ], Material.prototype, "name", void 0);
  35948. __decorate([
  35949. BABYLON.serialize()
  35950. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35951. __decorate([
  35952. BABYLON.serialize()
  35953. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35954. __decorate([
  35955. BABYLON.serialize()
  35956. ], Material.prototype, "state", void 0);
  35957. __decorate([
  35958. BABYLON.serialize("alpha")
  35959. ], Material.prototype, "_alpha", void 0);
  35960. __decorate([
  35961. BABYLON.serialize("backFaceCulling")
  35962. ], Material.prototype, "_backFaceCulling", void 0);
  35963. __decorate([
  35964. BABYLON.serialize()
  35965. ], Material.prototype, "sideOrientation", void 0);
  35966. __decorate([
  35967. BABYLON.serialize("alphaMode")
  35968. ], Material.prototype, "_alphaMode", void 0);
  35969. __decorate([
  35970. BABYLON.serialize()
  35971. ], Material.prototype, "_needDepthPrePass", void 0);
  35972. __decorate([
  35973. BABYLON.serialize()
  35974. ], Material.prototype, "disableDepthWrite", void 0);
  35975. __decorate([
  35976. BABYLON.serialize()
  35977. ], Material.prototype, "forceDepthWrite", void 0);
  35978. __decorate([
  35979. BABYLON.serialize()
  35980. ], Material.prototype, "separateCullingPass", void 0);
  35981. __decorate([
  35982. BABYLON.serialize("fogEnabled")
  35983. ], Material.prototype, "_fogEnabled", void 0);
  35984. __decorate([
  35985. BABYLON.serialize()
  35986. ], Material.prototype, "pointSize", void 0);
  35987. __decorate([
  35988. BABYLON.serialize()
  35989. ], Material.prototype, "zOffset", void 0);
  35990. __decorate([
  35991. BABYLON.serialize()
  35992. ], Material.prototype, "wireframe", null);
  35993. __decorate([
  35994. BABYLON.serialize()
  35995. ], Material.prototype, "pointsCloud", null);
  35996. __decorate([
  35997. BABYLON.serialize()
  35998. ], Material.prototype, "fillMode", null);
  35999. return Material;
  36000. }());
  36001. BABYLON.Material = Material;
  36002. })(BABYLON || (BABYLON = {}));
  36003. //# sourceMappingURL=babylon.material.js.map
  36004. var BABYLON;
  36005. (function (BABYLON) {
  36006. var UniformBuffer = /** @class */ (function () {
  36007. /**
  36008. * Uniform buffer objects.
  36009. *
  36010. * Handles blocks of uniform on the GPU.
  36011. *
  36012. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36013. *
  36014. * For more information, please refer to :
  36015. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36016. */
  36017. function UniformBuffer(engine, data, dynamic) {
  36018. this._engine = engine;
  36019. this._noUBO = !engine.supportsUniformBuffers;
  36020. this._dynamic = dynamic;
  36021. this._data = data || [];
  36022. this._uniformLocations = {};
  36023. this._uniformSizes = {};
  36024. this._uniformLocationPointer = 0;
  36025. this._needSync = false;
  36026. if (this._noUBO) {
  36027. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36028. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36029. this.updateFloat = this._updateFloatForEffect;
  36030. this.updateFloat2 = this._updateFloat2ForEffect;
  36031. this.updateFloat3 = this._updateFloat3ForEffect;
  36032. this.updateFloat4 = this._updateFloat4ForEffect;
  36033. this.updateMatrix = this._updateMatrixForEffect;
  36034. this.updateVector3 = this._updateVector3ForEffect;
  36035. this.updateVector4 = this._updateVector4ForEffect;
  36036. this.updateColor3 = this._updateColor3ForEffect;
  36037. this.updateColor4 = this._updateColor4ForEffect;
  36038. }
  36039. else {
  36040. this._engine._uniformBuffers.push(this);
  36041. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36042. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36043. this.updateFloat = this._updateFloatForUniform;
  36044. this.updateFloat2 = this._updateFloat2ForUniform;
  36045. this.updateFloat3 = this._updateFloat3ForUniform;
  36046. this.updateFloat4 = this._updateFloat4ForUniform;
  36047. this.updateMatrix = this._updateMatrixForUniform;
  36048. this.updateVector3 = this._updateVector3ForUniform;
  36049. this.updateVector4 = this._updateVector4ForUniform;
  36050. this.updateColor3 = this._updateColor3ForUniform;
  36051. this.updateColor4 = this._updateColor4ForUniform;
  36052. }
  36053. }
  36054. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36055. // Properties
  36056. /**
  36057. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36058. * or just falling back on setUniformXXX calls.
  36059. */
  36060. get: function () {
  36061. return !this._noUBO;
  36062. },
  36063. enumerable: true,
  36064. configurable: true
  36065. });
  36066. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36067. /**
  36068. * Indicates if the WebGL underlying uniform buffer is in sync
  36069. * with the javascript cache data.
  36070. */
  36071. get: function () {
  36072. return !this._needSync;
  36073. },
  36074. enumerable: true,
  36075. configurable: true
  36076. });
  36077. /**
  36078. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36079. * Also, a dynamic UniformBuffer will disable cache verification and always
  36080. * update the underlying WebGL uniform buffer to the GPU.
  36081. */
  36082. UniformBuffer.prototype.isDynamic = function () {
  36083. return this._dynamic !== undefined;
  36084. };
  36085. /**
  36086. * The data cache on JS side.
  36087. */
  36088. UniformBuffer.prototype.getData = function () {
  36089. return this._bufferData;
  36090. };
  36091. /**
  36092. * The underlying WebGL Uniform buffer.
  36093. */
  36094. UniformBuffer.prototype.getBuffer = function () {
  36095. return this._buffer;
  36096. };
  36097. /**
  36098. * std140 layout specifies how to align data within an UBO structure.
  36099. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36100. * for specs.
  36101. */
  36102. UniformBuffer.prototype._fillAlignment = function (size) {
  36103. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36104. // and 4x4 matrices
  36105. // TODO : change if other types are used
  36106. var alignment;
  36107. if (size <= 2) {
  36108. alignment = size;
  36109. }
  36110. else {
  36111. alignment = 4;
  36112. }
  36113. if ((this._uniformLocationPointer % alignment) !== 0) {
  36114. var oldPointer = this._uniformLocationPointer;
  36115. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36116. var diff = this._uniformLocationPointer - oldPointer;
  36117. for (var i = 0; i < diff; i++) {
  36118. this._data.push(0);
  36119. }
  36120. }
  36121. };
  36122. /**
  36123. * Adds an uniform in the buffer.
  36124. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36125. * for the layout to be correct !
  36126. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36127. * @param {number|number[]} size Data size, or data directly.
  36128. */
  36129. UniformBuffer.prototype.addUniform = function (name, size) {
  36130. if (this._noUBO) {
  36131. return;
  36132. }
  36133. if (this._uniformLocations[name] !== undefined) {
  36134. // Already existing uniform
  36135. return;
  36136. }
  36137. // This function must be called in the order of the shader layout !
  36138. // size can be the size of the uniform, or data directly
  36139. var data;
  36140. if (size instanceof Array) {
  36141. data = size;
  36142. size = data.length;
  36143. }
  36144. else {
  36145. size = size;
  36146. data = [];
  36147. // Fill with zeros
  36148. for (var i = 0; i < size; i++) {
  36149. data.push(0);
  36150. }
  36151. }
  36152. this._fillAlignment(size);
  36153. this._uniformSizes[name] = size;
  36154. this._uniformLocations[name] = this._uniformLocationPointer;
  36155. this._uniformLocationPointer += size;
  36156. for (var i = 0; i < size; i++) {
  36157. this._data.push(data[i]);
  36158. }
  36159. this._needSync = true;
  36160. };
  36161. /**
  36162. * Wrapper for addUniform.
  36163. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36164. * @param {Matrix} mat A 4x4 matrix.
  36165. */
  36166. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36167. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36168. };
  36169. /**
  36170. * Wrapper for addUniform.
  36171. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36172. * @param {number} x
  36173. * @param {number} y
  36174. */
  36175. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36176. var temp = [x, y];
  36177. this.addUniform(name, temp);
  36178. };
  36179. /**
  36180. * Wrapper for addUniform.
  36181. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36182. * @param {number} x
  36183. * @param {number} y
  36184. * @param {number} z
  36185. */
  36186. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36187. var temp = [x, y, z];
  36188. this.addUniform(name, temp);
  36189. };
  36190. /**
  36191. * Wrapper for addUniform.
  36192. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36193. * @param {Color3} color
  36194. */
  36195. UniformBuffer.prototype.addColor3 = function (name, color) {
  36196. var temp = new Array();
  36197. color.toArray(temp);
  36198. this.addUniform(name, temp);
  36199. };
  36200. /**
  36201. * Wrapper for addUniform.
  36202. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36203. * @param {Color3} color
  36204. * @param {number} alpha
  36205. */
  36206. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36207. var temp = new Array();
  36208. color.toArray(temp);
  36209. temp.push(alpha);
  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 {Vector3} vector
  36216. */
  36217. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36218. var temp = new Array();
  36219. vector.toArray(temp);
  36220. this.addUniform(name, temp);
  36221. };
  36222. /**
  36223. * Wrapper for addUniform.
  36224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36225. */
  36226. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36227. this.addUniform(name, 12);
  36228. };
  36229. /**
  36230. * Wrapper for addUniform.
  36231. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36232. */
  36233. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36234. this.addUniform(name, 8);
  36235. };
  36236. /**
  36237. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36238. */
  36239. UniformBuffer.prototype.create = function () {
  36240. if (this._noUBO) {
  36241. return;
  36242. }
  36243. if (this._buffer) {
  36244. return; // nothing to do
  36245. }
  36246. // See spec, alignment must be filled as a vec4
  36247. this._fillAlignment(4);
  36248. this._bufferData = new Float32Array(this._data);
  36249. this._rebuild();
  36250. this._needSync = true;
  36251. };
  36252. UniformBuffer.prototype._rebuild = function () {
  36253. if (this._noUBO) {
  36254. return;
  36255. }
  36256. if (this._dynamic) {
  36257. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36258. }
  36259. else {
  36260. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36261. }
  36262. };
  36263. /**
  36264. * Updates the WebGL Uniform Buffer on the GPU.
  36265. * If the `dynamic` flag is set to true, no cache comparison is done.
  36266. * Otherwise, the buffer will be updated only if the cache differs.
  36267. */
  36268. UniformBuffer.prototype.update = function () {
  36269. if (!this._buffer) {
  36270. this.create();
  36271. return;
  36272. }
  36273. if (!this._dynamic && !this._needSync) {
  36274. return;
  36275. }
  36276. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36277. this._needSync = false;
  36278. };
  36279. /**
  36280. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36281. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36282. * @param {number[]|Float32Array} data Flattened data
  36283. * @param {number} size Size of the data.
  36284. */
  36285. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36286. var location = this._uniformLocations[uniformName];
  36287. if (location === undefined) {
  36288. if (this._buffer) {
  36289. // Cannot add an uniform if the buffer is already created
  36290. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36291. return;
  36292. }
  36293. this.addUniform(uniformName, size);
  36294. location = this._uniformLocations[uniformName];
  36295. }
  36296. if (!this._buffer) {
  36297. this.create();
  36298. }
  36299. if (!this._dynamic) {
  36300. // Cache for static uniform buffers
  36301. var changed = false;
  36302. for (var i = 0; i < size; i++) {
  36303. if (this._bufferData[location + i] !== data[i]) {
  36304. changed = true;
  36305. this._bufferData[location + i] = data[i];
  36306. }
  36307. }
  36308. this._needSync = this._needSync || changed;
  36309. }
  36310. else {
  36311. // No cache for dynamic
  36312. for (var i = 0; i < size; i++) {
  36313. this._bufferData[location + i] = data[i];
  36314. }
  36315. }
  36316. };
  36317. // Update methods
  36318. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36319. // To match std140, matrix must be realigned
  36320. for (var i = 0; i < 3; i++) {
  36321. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36322. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36323. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36324. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36325. }
  36326. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36327. };
  36328. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36329. this._currentEffect.setMatrix3x3(name, matrix);
  36330. };
  36331. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36332. this._currentEffect.setMatrix2x2(name, matrix);
  36333. };
  36334. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36335. // To match std140, matrix must be realigned
  36336. for (var i = 0; i < 2; i++) {
  36337. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36338. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36339. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36340. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36341. }
  36342. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36343. };
  36344. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36345. this._currentEffect.setFloat(name, x);
  36346. };
  36347. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36348. UniformBuffer._tempBuffer[0] = x;
  36349. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36350. };
  36351. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36352. if (suffix === void 0) { suffix = ""; }
  36353. this._currentEffect.setFloat2(name + suffix, x, y);
  36354. };
  36355. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36356. if (suffix === void 0) { suffix = ""; }
  36357. UniformBuffer._tempBuffer[0] = x;
  36358. UniformBuffer._tempBuffer[1] = y;
  36359. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36360. };
  36361. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36362. if (suffix === void 0) { suffix = ""; }
  36363. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36364. };
  36365. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36366. if (suffix === void 0) { suffix = ""; }
  36367. UniformBuffer._tempBuffer[0] = x;
  36368. UniformBuffer._tempBuffer[1] = y;
  36369. UniformBuffer._tempBuffer[2] = z;
  36370. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36371. };
  36372. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36373. if (suffix === void 0) { suffix = ""; }
  36374. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36375. };
  36376. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36377. if (suffix === void 0) { suffix = ""; }
  36378. UniformBuffer._tempBuffer[0] = x;
  36379. UniformBuffer._tempBuffer[1] = y;
  36380. UniformBuffer._tempBuffer[2] = z;
  36381. UniformBuffer._tempBuffer[3] = w;
  36382. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36383. };
  36384. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36385. this._currentEffect.setMatrix(name, mat);
  36386. };
  36387. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36388. this.updateUniform(name, mat.toArray(), 16);
  36389. };
  36390. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36391. this._currentEffect.setVector3(name, vector);
  36392. };
  36393. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36394. vector.toArray(UniformBuffer._tempBuffer);
  36395. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36396. };
  36397. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36398. this._currentEffect.setVector4(name, vector);
  36399. };
  36400. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36401. vector.toArray(UniformBuffer._tempBuffer);
  36402. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36403. };
  36404. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36405. if (suffix === void 0) { suffix = ""; }
  36406. this._currentEffect.setColor3(name + suffix, color);
  36407. };
  36408. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36409. if (suffix === void 0) { suffix = ""; }
  36410. color.toArray(UniformBuffer._tempBuffer);
  36411. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36412. };
  36413. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36414. if (suffix === void 0) { suffix = ""; }
  36415. this._currentEffect.setColor4(name + suffix, color, alpha);
  36416. };
  36417. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36418. if (suffix === void 0) { suffix = ""; }
  36419. color.toArray(UniformBuffer._tempBuffer);
  36420. UniformBuffer._tempBuffer[3] = alpha;
  36421. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36422. };
  36423. /**
  36424. * Sets a sampler uniform on the effect.
  36425. * @param {string} name Name of the sampler.
  36426. * @param {Texture} texture
  36427. */
  36428. UniformBuffer.prototype.setTexture = function (name, texture) {
  36429. this._currentEffect.setTexture(name, texture);
  36430. };
  36431. /**
  36432. * Directly updates the value of the uniform in the cache AND on the GPU.
  36433. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36434. * @param {number[]|Float32Array} data Flattened data
  36435. */
  36436. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36437. this.updateUniform(uniformName, data, data.length);
  36438. this.update();
  36439. };
  36440. /**
  36441. * Binds this uniform buffer to an effect.
  36442. * @param {Effect} effect
  36443. * @param {string} name Name of the uniform block in the shader.
  36444. */
  36445. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36446. this._currentEffect = effect;
  36447. if (this._noUBO || !this._buffer) {
  36448. return;
  36449. }
  36450. effect.bindUniformBuffer(this._buffer, name);
  36451. };
  36452. /**
  36453. * Disposes the uniform buffer.
  36454. */
  36455. UniformBuffer.prototype.dispose = function () {
  36456. if (this._noUBO) {
  36457. return;
  36458. }
  36459. var index = this._engine._uniformBuffers.indexOf(this);
  36460. if (index !== -1) {
  36461. this._engine._uniformBuffers.splice(index, 1);
  36462. }
  36463. if (!this._buffer) {
  36464. return;
  36465. }
  36466. if (this._engine._releaseBuffer(this._buffer)) {
  36467. this._buffer = null;
  36468. }
  36469. };
  36470. // Pool for avoiding memory leaks
  36471. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36472. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36473. return UniformBuffer;
  36474. }());
  36475. BABYLON.UniformBuffer = UniformBuffer;
  36476. })(BABYLON || (BABYLON = {}));
  36477. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36478. var BABYLON;
  36479. (function (BABYLON) {
  36480. /**
  36481. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36482. */
  36483. var VertexData = /** @class */ (function () {
  36484. function VertexData() {
  36485. }
  36486. /**
  36487. * Uses the passed data array to set the set the values for the specified kind of data
  36488. * @param data a linear array of floating numbers
  36489. * @param kind the type of data that is being set, eg positions, colors etc
  36490. */
  36491. VertexData.prototype.set = function (data, kind) {
  36492. switch (kind) {
  36493. case BABYLON.VertexBuffer.PositionKind:
  36494. this.positions = data;
  36495. break;
  36496. case BABYLON.VertexBuffer.NormalKind:
  36497. this.normals = data;
  36498. break;
  36499. case BABYLON.VertexBuffer.TangentKind:
  36500. this.tangents = data;
  36501. break;
  36502. case BABYLON.VertexBuffer.UVKind:
  36503. this.uvs = data;
  36504. break;
  36505. case BABYLON.VertexBuffer.UV2Kind:
  36506. this.uvs2 = data;
  36507. break;
  36508. case BABYLON.VertexBuffer.UV3Kind:
  36509. this.uvs3 = data;
  36510. break;
  36511. case BABYLON.VertexBuffer.UV4Kind:
  36512. this.uvs4 = data;
  36513. break;
  36514. case BABYLON.VertexBuffer.UV5Kind:
  36515. this.uvs5 = data;
  36516. break;
  36517. case BABYLON.VertexBuffer.UV6Kind:
  36518. this.uvs6 = data;
  36519. break;
  36520. case BABYLON.VertexBuffer.ColorKind:
  36521. this.colors = data;
  36522. break;
  36523. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36524. this.matricesIndices = data;
  36525. break;
  36526. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36527. this.matricesWeights = data;
  36528. break;
  36529. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36530. this.matricesIndicesExtra = data;
  36531. break;
  36532. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36533. this.matricesWeightsExtra = data;
  36534. break;
  36535. }
  36536. };
  36537. /**
  36538. * Associates the vertexData to the passed Mesh.
  36539. * Sets it as updatable or not (default `false`)
  36540. * @param mesh the mesh the vertexData is applied to
  36541. * @param updatable when used and having the value true allows new data to update the vertexData
  36542. * @returns the VertexData
  36543. */
  36544. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36545. this._applyTo(mesh, updatable);
  36546. return this;
  36547. };
  36548. /**
  36549. * Associates the vertexData to the passed Geometry.
  36550. * Sets it as updatable or not (default `false`)
  36551. * @param geometry the geometry the vertexData is applied to
  36552. * @param updatable when used and having the value true allows new data to update the vertexData
  36553. * @returns VertexData
  36554. */
  36555. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36556. this._applyTo(geometry, updatable);
  36557. return this;
  36558. };
  36559. /**
  36560. * Updates the associated mesh
  36561. * @param mesh the mesh to be updated
  36562. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36563. * @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
  36564. * @returns VertexData
  36565. */
  36566. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36567. this._update(mesh);
  36568. return this;
  36569. };
  36570. /**
  36571. * Updates the associated geometry
  36572. * @param geometry the geometry to be updated
  36573. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36574. * @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
  36575. * @returns VertexData.
  36576. */
  36577. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36578. this._update(geometry);
  36579. return this;
  36580. };
  36581. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36582. if (updatable === void 0) { updatable = false; }
  36583. if (this.positions) {
  36584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36585. }
  36586. if (this.normals) {
  36587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36588. }
  36589. if (this.tangents) {
  36590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36591. }
  36592. if (this.uvs) {
  36593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36594. }
  36595. if (this.uvs2) {
  36596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36597. }
  36598. if (this.uvs3) {
  36599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36600. }
  36601. if (this.uvs4) {
  36602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36603. }
  36604. if (this.uvs5) {
  36605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36606. }
  36607. if (this.uvs6) {
  36608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36609. }
  36610. if (this.colors) {
  36611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36612. }
  36613. if (this.matricesIndices) {
  36614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36615. }
  36616. if (this.matricesWeights) {
  36617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36618. }
  36619. if (this.matricesIndicesExtra) {
  36620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36621. }
  36622. if (this.matricesWeightsExtra) {
  36623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36624. }
  36625. if (this.indices) {
  36626. meshOrGeometry.setIndices(this.indices, null, updatable);
  36627. }
  36628. else {
  36629. meshOrGeometry.setIndices([], null);
  36630. }
  36631. return this;
  36632. };
  36633. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36634. if (this.positions) {
  36635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36636. }
  36637. if (this.normals) {
  36638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36639. }
  36640. if (this.tangents) {
  36641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36642. }
  36643. if (this.uvs) {
  36644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36645. }
  36646. if (this.uvs2) {
  36647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36648. }
  36649. if (this.uvs3) {
  36650. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36651. }
  36652. if (this.uvs4) {
  36653. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36654. }
  36655. if (this.uvs5) {
  36656. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36657. }
  36658. if (this.uvs6) {
  36659. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36660. }
  36661. if (this.colors) {
  36662. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36663. }
  36664. if (this.matricesIndices) {
  36665. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36666. }
  36667. if (this.matricesWeights) {
  36668. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36669. }
  36670. if (this.matricesIndicesExtra) {
  36671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36672. }
  36673. if (this.matricesWeightsExtra) {
  36674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36675. }
  36676. if (this.indices) {
  36677. meshOrGeometry.setIndices(this.indices, null);
  36678. }
  36679. return this;
  36680. };
  36681. /**
  36682. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36683. * @param matrix the transforming matrix
  36684. * @returns the VertexData
  36685. */
  36686. VertexData.prototype.transform = function (matrix) {
  36687. var transformed = BABYLON.Vector3.Zero();
  36688. var index;
  36689. if (this.positions) {
  36690. var position = BABYLON.Vector3.Zero();
  36691. for (index = 0; index < this.positions.length; index += 3) {
  36692. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36693. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36694. this.positions[index] = transformed.x;
  36695. this.positions[index + 1] = transformed.y;
  36696. this.positions[index + 2] = transformed.z;
  36697. }
  36698. }
  36699. if (this.normals) {
  36700. var normal = BABYLON.Vector3.Zero();
  36701. for (index = 0; index < this.normals.length; index += 3) {
  36702. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36703. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36704. this.normals[index] = transformed.x;
  36705. this.normals[index + 1] = transformed.y;
  36706. this.normals[index + 2] = transformed.z;
  36707. }
  36708. }
  36709. if (this.tangents) {
  36710. var tangent = BABYLON.Vector4.Zero();
  36711. var tangentTransformed = BABYLON.Vector4.Zero();
  36712. for (index = 0; index < this.tangents.length; index += 4) {
  36713. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36714. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36715. this.tangents[index] = tangentTransformed.x;
  36716. this.tangents[index + 1] = tangentTransformed.y;
  36717. this.tangents[index + 2] = tangentTransformed.z;
  36718. this.tangents[index + 3] = tangentTransformed.w;
  36719. }
  36720. }
  36721. return this;
  36722. };
  36723. /**
  36724. * Merges the passed VertexData into the current one
  36725. * @param other the VertexData to be merged into the current one
  36726. * @returns the modified VertexData
  36727. */
  36728. VertexData.prototype.merge = function (other) {
  36729. this._validate();
  36730. other._validate();
  36731. if (!this.normals !== !other.normals ||
  36732. !this.tangents !== !other.tangents ||
  36733. !this.uvs !== !other.uvs ||
  36734. !this.uvs2 !== !other.uvs2 ||
  36735. !this.uvs3 !== !other.uvs3 ||
  36736. !this.uvs4 !== !other.uvs4 ||
  36737. !this.uvs5 !== !other.uvs5 ||
  36738. !this.uvs6 !== !other.uvs6 ||
  36739. !this.colors !== !other.colors ||
  36740. !this.matricesIndices !== !other.matricesIndices ||
  36741. !this.matricesWeights !== !other.matricesWeights ||
  36742. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36743. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36744. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36745. }
  36746. if (other.indices) {
  36747. if (!this.indices) {
  36748. this.indices = [];
  36749. }
  36750. var offset = this.positions ? this.positions.length / 3 : 0;
  36751. for (var index = 0; index < other.indices.length; index++) {
  36752. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36753. this.indices.push(other.indices[index] + offset);
  36754. }
  36755. }
  36756. this.positions = this._mergeElement(this.positions, other.positions);
  36757. this.normals = this._mergeElement(this.normals, other.normals);
  36758. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36759. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36760. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36761. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36762. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36763. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36764. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36765. this.colors = this._mergeElement(this.colors, other.colors);
  36766. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36767. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36768. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36769. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36770. return this;
  36771. };
  36772. VertexData.prototype._mergeElement = function (source, other) {
  36773. if (!source) {
  36774. return other;
  36775. }
  36776. if (!other) {
  36777. return source;
  36778. }
  36779. var len = other.length + source.length;
  36780. var isSrcTypedArray = source instanceof Float32Array;
  36781. var isOthTypedArray = other instanceof Float32Array;
  36782. // use non-loop method when the source is Float32Array
  36783. if (isSrcTypedArray) {
  36784. var ret32 = new Float32Array(len);
  36785. ret32.set(source);
  36786. ret32.set(other, source.length);
  36787. return ret32;
  36788. // source is number[], when other is also use concat
  36789. }
  36790. else if (!isOthTypedArray) {
  36791. return source.concat(other);
  36792. // source is a number[], but other is a Float32Array, loop required
  36793. }
  36794. else {
  36795. var ret = source.slice(0); // copy source to a separate array
  36796. for (var i = 0, len = other.length; i < len; i++) {
  36797. ret.push(other[i]);
  36798. }
  36799. return ret;
  36800. }
  36801. };
  36802. VertexData.prototype._validate = function () {
  36803. if (!this.positions) {
  36804. throw new Error("Positions are required");
  36805. }
  36806. var getElementCount = function (kind, values) {
  36807. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36808. if ((values.length % stride) !== 0) {
  36809. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36810. }
  36811. return values.length / stride;
  36812. };
  36813. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36814. var validateElementCount = function (kind, values) {
  36815. var elementCount = getElementCount(kind, values);
  36816. if (elementCount !== positionsElementCount) {
  36817. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36818. }
  36819. };
  36820. if (this.normals)
  36821. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36822. if (this.tangents)
  36823. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36824. if (this.uvs)
  36825. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36826. if (this.uvs2)
  36827. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36828. if (this.uvs3)
  36829. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36830. if (this.uvs4)
  36831. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36832. if (this.uvs5)
  36833. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36834. if (this.uvs6)
  36835. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36836. if (this.colors)
  36837. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36838. if (this.matricesIndices)
  36839. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36840. if (this.matricesWeights)
  36841. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36842. if (this.matricesIndicesExtra)
  36843. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36844. if (this.matricesWeightsExtra)
  36845. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36846. };
  36847. /**
  36848. * Serializes the VertexData
  36849. * @returns a serialized object
  36850. */
  36851. VertexData.prototype.serialize = function () {
  36852. var serializationObject = this.serialize();
  36853. if (this.positions) {
  36854. serializationObject.positions = this.positions;
  36855. }
  36856. if (this.normals) {
  36857. serializationObject.normals = this.normals;
  36858. }
  36859. if (this.tangents) {
  36860. serializationObject.tangents = this.tangents;
  36861. }
  36862. if (this.uvs) {
  36863. serializationObject.uvs = this.uvs;
  36864. }
  36865. if (this.uvs2) {
  36866. serializationObject.uvs2 = this.uvs2;
  36867. }
  36868. if (this.uvs3) {
  36869. serializationObject.uvs3 = this.uvs3;
  36870. }
  36871. if (this.uvs4) {
  36872. serializationObject.uvs4 = this.uvs4;
  36873. }
  36874. if (this.uvs5) {
  36875. serializationObject.uvs5 = this.uvs5;
  36876. }
  36877. if (this.uvs6) {
  36878. serializationObject.uvs6 = this.uvs6;
  36879. }
  36880. if (this.colors) {
  36881. serializationObject.colors = this.colors;
  36882. }
  36883. if (this.matricesIndices) {
  36884. serializationObject.matricesIndices = this.matricesIndices;
  36885. serializationObject.matricesIndices._isExpanded = true;
  36886. }
  36887. if (this.matricesWeights) {
  36888. serializationObject.matricesWeights = this.matricesWeights;
  36889. }
  36890. if (this.matricesIndicesExtra) {
  36891. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36892. serializationObject.matricesIndicesExtra._isExpanded = true;
  36893. }
  36894. if (this.matricesWeightsExtra) {
  36895. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36896. }
  36897. serializationObject.indices = this.indices;
  36898. return serializationObject;
  36899. };
  36900. // Statics
  36901. /**
  36902. * Extracts the vertexData from a mesh
  36903. * @param mesh the mesh from which to extract the VertexData
  36904. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36905. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36906. * @returns the object VertexData associated to the passed mesh
  36907. */
  36908. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36909. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36910. };
  36911. /**
  36912. * Extracts the vertexData from the geometry
  36913. * @param geometry the geometry from which to extract the VertexData
  36914. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36915. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36916. * @returns the object VertexData associated to the passed mesh
  36917. */
  36918. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36919. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36920. };
  36921. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36922. var result = new VertexData();
  36923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36924. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36925. }
  36926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36927. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36928. }
  36929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36930. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36931. }
  36932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36933. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36934. }
  36935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36936. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36937. }
  36938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36939. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36940. }
  36941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36942. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36943. }
  36944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36945. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36946. }
  36947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36948. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36949. }
  36950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36951. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36952. }
  36953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36954. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36955. }
  36956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36957. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36958. }
  36959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36960. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36961. }
  36962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36963. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36964. }
  36965. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36966. return result;
  36967. };
  36968. /**
  36969. * Creates the VertexData for a Ribbon
  36970. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36971. * * pathArray array of paths, each of which an array of successive Vector3
  36972. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36973. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36974. * * 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
  36975. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36976. * * 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)
  36977. * * 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)
  36978. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36979. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36980. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36981. * @returns the VertexData of the ribbon
  36982. */
  36983. VertexData.CreateRibbon = function (options) {
  36984. var pathArray = options.pathArray;
  36985. var closeArray = options.closeArray || false;
  36986. var closePath = options.closePath || false;
  36987. var invertUV = options.invertUV || false;
  36988. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36989. var offset = options.offset || defaultOffset;
  36990. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36991. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36992. var customUV = options.uvs;
  36993. var customColors = options.colors;
  36994. var positions = [];
  36995. var indices = [];
  36996. var normals = [];
  36997. var uvs = [];
  36998. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36999. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37000. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37001. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37002. var minlg; // minimal length among all paths from pathArray
  37003. var lg = []; // array of path lengths : nb of vertex per path
  37004. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37005. var p; // path iterator
  37006. var i; // point iterator
  37007. var j; // point iterator
  37008. // if single path in pathArray
  37009. if (pathArray.length < 2) {
  37010. var ar1 = [];
  37011. var ar2 = [];
  37012. for (i = 0; i < pathArray[0].length - offset; i++) {
  37013. ar1.push(pathArray[0][i]);
  37014. ar2.push(pathArray[0][i + offset]);
  37015. }
  37016. pathArray = [ar1, ar2];
  37017. }
  37018. // positions and horizontal distances (u)
  37019. var idc = 0;
  37020. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37021. var path;
  37022. var l;
  37023. minlg = pathArray[0].length;
  37024. var vectlg;
  37025. var dist;
  37026. for (p = 0; p < pathArray.length; p++) {
  37027. uTotalDistance[p] = 0;
  37028. us[p] = [0];
  37029. path = pathArray[p];
  37030. l = path.length;
  37031. minlg = (minlg < l) ? minlg : l;
  37032. j = 0;
  37033. while (j < l) {
  37034. positions.push(path[j].x, path[j].y, path[j].z);
  37035. if (j > 0) {
  37036. vectlg = path[j].subtract(path[j - 1]).length();
  37037. dist = vectlg + uTotalDistance[p];
  37038. us[p].push(dist);
  37039. uTotalDistance[p] = dist;
  37040. }
  37041. j++;
  37042. }
  37043. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37044. j--;
  37045. positions.push(path[0].x, path[0].y, path[0].z);
  37046. vectlg = path[j].subtract(path[0]).length();
  37047. dist = vectlg + uTotalDistance[p];
  37048. us[p].push(dist);
  37049. uTotalDistance[p] = dist;
  37050. }
  37051. lg[p] = l + closePathCorr;
  37052. idx[p] = idc;
  37053. idc += (l + closePathCorr);
  37054. }
  37055. // vertical distances (v)
  37056. var path1;
  37057. var path2;
  37058. var vertex1 = null;
  37059. var vertex2 = null;
  37060. for (i = 0; i < minlg + closePathCorr; i++) {
  37061. vTotalDistance[i] = 0;
  37062. vs[i] = [0];
  37063. for (p = 0; p < pathArray.length - 1; p++) {
  37064. path1 = pathArray[p];
  37065. path2 = pathArray[p + 1];
  37066. if (i === minlg) { // closePath
  37067. vertex1 = path1[0];
  37068. vertex2 = path2[0];
  37069. }
  37070. else {
  37071. vertex1 = path1[i];
  37072. vertex2 = path2[i];
  37073. }
  37074. vectlg = vertex2.subtract(vertex1).length();
  37075. dist = vectlg + vTotalDistance[i];
  37076. vs[i].push(dist);
  37077. vTotalDistance[i] = dist;
  37078. }
  37079. if (closeArray && vertex2 && vertex1) {
  37080. path1 = pathArray[p];
  37081. path2 = pathArray[0];
  37082. if (i === minlg) { // closePath
  37083. vertex2 = path2[0];
  37084. }
  37085. vectlg = vertex2.subtract(vertex1).length();
  37086. dist = vectlg + vTotalDistance[i];
  37087. vTotalDistance[i] = dist;
  37088. }
  37089. }
  37090. // uvs
  37091. var u;
  37092. var v;
  37093. if (customUV) {
  37094. for (p = 0; p < customUV.length; p++) {
  37095. uvs.push(customUV[p].x, customUV[p].y);
  37096. }
  37097. }
  37098. else {
  37099. for (p = 0; p < pathArray.length; p++) {
  37100. for (i = 0; i < minlg + closePathCorr; i++) {
  37101. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37102. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37103. if (invertUV) {
  37104. uvs.push(v, u);
  37105. }
  37106. else {
  37107. uvs.push(u, v);
  37108. }
  37109. }
  37110. }
  37111. }
  37112. // indices
  37113. p = 0; // path index
  37114. var pi = 0; // positions array index
  37115. var l1 = lg[p] - 1; // path1 length
  37116. var l2 = lg[p + 1] - 1; // path2 length
  37117. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37118. var shft = idx[1] - idx[0]; // shift
  37119. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37120. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37121. // 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
  37122. indices.push(pi, pi + shft, pi + 1);
  37123. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37124. pi += 1;
  37125. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37126. p++;
  37127. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37128. shft = idx[0] - idx[p];
  37129. l1 = lg[p] - 1;
  37130. l2 = lg[0] - 1;
  37131. }
  37132. else {
  37133. shft = idx[p + 1] - idx[p];
  37134. l1 = lg[p] - 1;
  37135. l2 = lg[p + 1] - 1;
  37136. }
  37137. pi = idx[p];
  37138. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37139. }
  37140. }
  37141. // normals
  37142. VertexData.ComputeNormals(positions, indices, normals);
  37143. if (closePath) { // update both the first and last vertex normals to their average value
  37144. var indexFirst = 0;
  37145. var indexLast = 0;
  37146. for (p = 0; p < pathArray.length; p++) {
  37147. indexFirst = idx[p] * 3;
  37148. if (p + 1 < pathArray.length) {
  37149. indexLast = (idx[p + 1] - 1) * 3;
  37150. }
  37151. else {
  37152. indexLast = normals.length - 3;
  37153. }
  37154. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37155. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37156. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37157. normals[indexLast] = normals[indexFirst];
  37158. normals[indexLast + 1] = normals[indexFirst + 1];
  37159. normals[indexLast + 2] = normals[indexFirst + 2];
  37160. }
  37161. }
  37162. // sides
  37163. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37164. // Colors
  37165. var colors = null;
  37166. if (customColors) {
  37167. colors = new Float32Array(customColors.length * 4);
  37168. for (var c = 0; c < customColors.length; c++) {
  37169. colors[c * 4] = customColors[c].r;
  37170. colors[c * 4 + 1] = customColors[c].g;
  37171. colors[c * 4 + 2] = customColors[c].b;
  37172. colors[c * 4 + 3] = customColors[c].a;
  37173. }
  37174. }
  37175. // Result
  37176. var vertexData = new VertexData();
  37177. var positions32 = new Float32Array(positions);
  37178. var normals32 = new Float32Array(normals);
  37179. var uvs32 = new Float32Array(uvs);
  37180. vertexData.indices = indices;
  37181. vertexData.positions = positions32;
  37182. vertexData.normals = normals32;
  37183. vertexData.uvs = uvs32;
  37184. if (colors) {
  37185. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37186. }
  37187. if (closePath) {
  37188. vertexData._idx = idx;
  37189. }
  37190. return vertexData;
  37191. };
  37192. /**
  37193. * Creates the VertexData for a box
  37194. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37195. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37196. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37197. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37198. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37199. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37200. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37201. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37202. * * 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)
  37203. * * 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)
  37204. * @returns the VertexData of the box
  37205. */
  37206. VertexData.CreateBox = function (options) {
  37207. var normalsSource = [
  37208. new BABYLON.Vector3(0, 0, 1),
  37209. new BABYLON.Vector3(0, 0, -1),
  37210. new BABYLON.Vector3(1, 0, 0),
  37211. new BABYLON.Vector3(-1, 0, 0),
  37212. new BABYLON.Vector3(0, 1, 0),
  37213. new BABYLON.Vector3(0, -1, 0)
  37214. ];
  37215. var indices = [];
  37216. var positions = [];
  37217. var normals = [];
  37218. var uvs = [];
  37219. var width = options.width || options.size || 1;
  37220. var height = options.height || options.size || 1;
  37221. var depth = options.depth || options.size || 1;
  37222. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37223. var faceUV = options.faceUV || new Array(6);
  37224. var faceColors = options.faceColors;
  37225. var colors = [];
  37226. // default face colors and UV if undefined
  37227. for (var f = 0; f < 6; f++) {
  37228. if (faceUV[f] === undefined) {
  37229. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37230. }
  37231. if (faceColors && faceColors[f] === undefined) {
  37232. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37233. }
  37234. }
  37235. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37236. // Create each face in turn.
  37237. for (var index = 0; index < normalsSource.length; index++) {
  37238. var normal = normalsSource[index];
  37239. // Get two vectors perpendicular to the face normal and to each other.
  37240. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37241. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37242. // Six indices (two triangles) per face.
  37243. var verticesLength = positions.length / 3;
  37244. indices.push(verticesLength);
  37245. indices.push(verticesLength + 1);
  37246. indices.push(verticesLength + 2);
  37247. indices.push(verticesLength);
  37248. indices.push(verticesLength + 2);
  37249. indices.push(verticesLength + 3);
  37250. // Four vertices per face.
  37251. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37252. positions.push(vertex.x, vertex.y, vertex.z);
  37253. normals.push(normal.x, normal.y, normal.z);
  37254. uvs.push(faceUV[index].z, faceUV[index].w);
  37255. if (faceColors) {
  37256. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37257. }
  37258. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37259. positions.push(vertex.x, vertex.y, vertex.z);
  37260. normals.push(normal.x, normal.y, normal.z);
  37261. uvs.push(faceUV[index].x, faceUV[index].w);
  37262. if (faceColors) {
  37263. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37264. }
  37265. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37266. positions.push(vertex.x, vertex.y, vertex.z);
  37267. normals.push(normal.x, normal.y, normal.z);
  37268. uvs.push(faceUV[index].x, faceUV[index].y);
  37269. if (faceColors) {
  37270. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37271. }
  37272. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37273. positions.push(vertex.x, vertex.y, vertex.z);
  37274. normals.push(normal.x, normal.y, normal.z);
  37275. uvs.push(faceUV[index].z, faceUV[index].y);
  37276. if (faceColors) {
  37277. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37278. }
  37279. }
  37280. // sides
  37281. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37282. // Result
  37283. var vertexData = new VertexData();
  37284. vertexData.indices = indices;
  37285. vertexData.positions = positions;
  37286. vertexData.normals = normals;
  37287. vertexData.uvs = uvs;
  37288. if (faceColors) {
  37289. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37290. vertexData.colors = totalColors;
  37291. }
  37292. return vertexData;
  37293. };
  37294. /**
  37295. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37296. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37297. * * segments sets the number of horizontal strips optional, default 32
  37298. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37299. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37300. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37301. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37302. * * 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
  37303. * * 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
  37304. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37305. * * 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)
  37306. * * 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)
  37307. * @returns the VertexData of the ellipsoid
  37308. */
  37309. VertexData.CreateSphere = function (options) {
  37310. var segments = options.segments || 32;
  37311. var diameterX = options.diameterX || options.diameter || 1;
  37312. var diameterY = options.diameterY || options.diameter || 1;
  37313. var diameterZ = options.diameterZ || options.diameter || 1;
  37314. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37315. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37317. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37318. var totalZRotationSteps = 2 + segments;
  37319. var totalYRotationSteps = 2 * totalZRotationSteps;
  37320. var indices = [];
  37321. var positions = [];
  37322. var normals = [];
  37323. var uvs = [];
  37324. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37325. var normalizedZ = zRotationStep / totalZRotationSteps;
  37326. var angleZ = normalizedZ * Math.PI * slice;
  37327. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37328. var normalizedY = yRotationStep / totalYRotationSteps;
  37329. var angleY = normalizedY * Math.PI * 2 * arc;
  37330. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37331. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37332. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37333. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37334. var vertex = complete.multiply(radius);
  37335. var normal = complete.divide(radius).normalize();
  37336. positions.push(vertex.x, vertex.y, vertex.z);
  37337. normals.push(normal.x, normal.y, normal.z);
  37338. uvs.push(normalizedY, normalizedZ);
  37339. }
  37340. if (zRotationStep > 0) {
  37341. var verticesCount = positions.length / 3;
  37342. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37343. indices.push((firstIndex));
  37344. indices.push((firstIndex + 1));
  37345. indices.push(firstIndex + totalYRotationSteps + 1);
  37346. indices.push((firstIndex + totalYRotationSteps + 1));
  37347. indices.push((firstIndex + 1));
  37348. indices.push((firstIndex + totalYRotationSteps + 2));
  37349. }
  37350. }
  37351. }
  37352. // Sides
  37353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37354. // Result
  37355. var vertexData = new VertexData();
  37356. vertexData.indices = indices;
  37357. vertexData.positions = positions;
  37358. vertexData.normals = normals;
  37359. vertexData.uvs = uvs;
  37360. return vertexData;
  37361. };
  37362. /**
  37363. * Creates the VertexData for a cylinder, cone or prism
  37364. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37365. * * height sets the height (y direction) of the cylinder, optional, default 2
  37366. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37367. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37368. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37369. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37370. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37371. * * 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
  37372. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37373. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37374. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37375. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37376. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37377. * * 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)
  37378. * * 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)
  37379. * @returns the VertexData of the cylinder, cone or prism
  37380. */
  37381. VertexData.CreateCylinder = function (options) {
  37382. var height = options.height || 2;
  37383. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37384. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37385. var tessellation = options.tessellation || 24;
  37386. var subdivisions = options.subdivisions || 1;
  37387. var hasRings = options.hasRings ? true : false;
  37388. var enclose = options.enclose ? true : false;
  37389. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37390. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37391. var faceUV = options.faceUV || new Array(3);
  37392. var faceColors = options.faceColors;
  37393. // default face colors and UV if undefined
  37394. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37395. var ringNb = (hasRings) ? subdivisions : 1;
  37396. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37397. var f;
  37398. for (f = 0; f < surfaceNb; f++) {
  37399. if (faceColors && faceColors[f] === undefined) {
  37400. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37401. }
  37402. }
  37403. for (f = 0; f < surfaceNb; f++) {
  37404. if (faceUV && faceUV[f] === undefined) {
  37405. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37406. }
  37407. }
  37408. var indices = new Array();
  37409. var positions = new Array();
  37410. var normals = new Array();
  37411. var uvs = new Array();
  37412. var colors = new Array();
  37413. var angle_step = Math.PI * 2 * arc / tessellation;
  37414. var angle;
  37415. var h;
  37416. var radius;
  37417. var tan = (diameterBottom - diameterTop) / 2 / height;
  37418. var ringVertex = BABYLON.Vector3.Zero();
  37419. var ringNormal = BABYLON.Vector3.Zero();
  37420. var ringFirstVertex = BABYLON.Vector3.Zero();
  37421. var ringFirstNormal = BABYLON.Vector3.Zero();
  37422. var quadNormal = BABYLON.Vector3.Zero();
  37423. var Y = BABYLON.Axis.Y;
  37424. // positions, normals, uvs
  37425. var i;
  37426. var j;
  37427. var r;
  37428. var ringIdx = 1;
  37429. var s = 1; // surface index
  37430. var cs = 0;
  37431. var v = 0;
  37432. for (i = 0; i <= subdivisions; i++) {
  37433. h = i / subdivisions;
  37434. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37435. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37436. for (r = 0; r < ringIdx; r++) {
  37437. if (hasRings) {
  37438. s += r;
  37439. }
  37440. if (enclose) {
  37441. s += 2 * r;
  37442. }
  37443. for (j = 0; j <= tessellation; j++) {
  37444. angle = j * angle_step;
  37445. // position
  37446. ringVertex.x = Math.cos(-angle) * radius;
  37447. ringVertex.y = -height / 2 + h * height;
  37448. ringVertex.z = Math.sin(-angle) * radius;
  37449. // normal
  37450. if (diameterTop === 0 && i === subdivisions) {
  37451. // if no top cap, reuse former normals
  37452. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37453. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37454. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37455. }
  37456. else {
  37457. ringNormal.x = ringVertex.x;
  37458. ringNormal.z = ringVertex.z;
  37459. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37460. ringNormal.normalize();
  37461. }
  37462. // keep first ring vertex values for enclose
  37463. if (j === 0) {
  37464. ringFirstVertex.copyFrom(ringVertex);
  37465. ringFirstNormal.copyFrom(ringNormal);
  37466. }
  37467. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37468. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37469. if (hasRings) {
  37470. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37471. }
  37472. else {
  37473. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37474. }
  37475. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37476. if (faceColors) {
  37477. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37478. }
  37479. }
  37480. // if enclose, add four vertices and their dedicated normals
  37481. if (arc !== 1 && enclose) {
  37482. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37483. positions.push(0, ringVertex.y, 0);
  37484. positions.push(0, ringVertex.y, 0);
  37485. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37486. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37487. quadNormal.normalize();
  37488. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37489. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37490. quadNormal.normalize();
  37491. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37492. if (hasRings) {
  37493. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37494. }
  37495. else {
  37496. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37497. }
  37498. uvs.push(faceUV[s + 1].x, v);
  37499. uvs.push(faceUV[s + 1].z, v);
  37500. if (hasRings) {
  37501. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37502. }
  37503. else {
  37504. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37505. }
  37506. uvs.push(faceUV[s + 2].x, v);
  37507. uvs.push(faceUV[s + 2].z, v);
  37508. if (faceColors) {
  37509. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37510. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37511. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37512. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37513. }
  37514. }
  37515. if (cs !== s) {
  37516. cs = s;
  37517. }
  37518. }
  37519. }
  37520. // indices
  37521. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37522. var s;
  37523. i = 0;
  37524. for (s = 0; s < subdivisions; s++) {
  37525. var i0 = 0;
  37526. var i1 = 0;
  37527. var i2 = 0;
  37528. var i3 = 0;
  37529. for (j = 0; j < tessellation; j++) {
  37530. i0 = i * (e + 1) + j;
  37531. i1 = (i + 1) * (e + 1) + j;
  37532. i2 = i * (e + 1) + (j + 1);
  37533. i3 = (i + 1) * (e + 1) + (j + 1);
  37534. indices.push(i0, i1, i2);
  37535. indices.push(i3, i2, i1);
  37536. }
  37537. if (arc !== 1 && enclose) { // if enclose, add two quads
  37538. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37539. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37540. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37541. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37542. }
  37543. i = (hasRings) ? (i + 2) : (i + 1);
  37544. }
  37545. // Caps
  37546. var createCylinderCap = function (isTop) {
  37547. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37548. if (radius === 0) {
  37549. return;
  37550. }
  37551. // Cap positions, normals & uvs
  37552. var angle;
  37553. var circleVector;
  37554. var i;
  37555. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37556. var c = null;
  37557. if (faceColors) {
  37558. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37559. }
  37560. // cap center
  37561. var vbase = positions.length / 3;
  37562. var offset = isTop ? height / 2 : -height / 2;
  37563. var center = new BABYLON.Vector3(0, offset, 0);
  37564. positions.push(center.x, center.y, center.z);
  37565. normals.push(0, isTop ? 1 : -1, 0);
  37566. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37567. if (c) {
  37568. colors.push(c.r, c.g, c.b, c.a);
  37569. }
  37570. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37571. for (i = 0; i <= tessellation; i++) {
  37572. angle = Math.PI * 2 * i * arc / tessellation;
  37573. var cos = Math.cos(-angle);
  37574. var sin = Math.sin(-angle);
  37575. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37576. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37577. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37578. normals.push(0, isTop ? 1 : -1, 0);
  37579. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37580. if (c) {
  37581. colors.push(c.r, c.g, c.b, c.a);
  37582. }
  37583. }
  37584. // Cap indices
  37585. for (i = 0; i < tessellation; i++) {
  37586. if (!isTop) {
  37587. indices.push(vbase);
  37588. indices.push(vbase + (i + 1));
  37589. indices.push(vbase + (i + 2));
  37590. }
  37591. else {
  37592. indices.push(vbase);
  37593. indices.push(vbase + (i + 2));
  37594. indices.push(vbase + (i + 1));
  37595. }
  37596. }
  37597. };
  37598. // add caps to geometry
  37599. createCylinderCap(false);
  37600. createCylinderCap(true);
  37601. // Sides
  37602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37603. var vertexData = new VertexData();
  37604. vertexData.indices = indices;
  37605. vertexData.positions = positions;
  37606. vertexData.normals = normals;
  37607. vertexData.uvs = uvs;
  37608. if (faceColors) {
  37609. vertexData.colors = colors;
  37610. }
  37611. return vertexData;
  37612. };
  37613. /**
  37614. * Creates the VertexData for a torus
  37615. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37616. * * diameter the diameter of the torus, optional default 1
  37617. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37618. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37619. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37620. * * 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)
  37621. * * 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)
  37622. * @returns the VertexData of the torus
  37623. */
  37624. VertexData.CreateTorus = function (options) {
  37625. var indices = [];
  37626. var positions = [];
  37627. var normals = [];
  37628. var uvs = [];
  37629. var diameter = options.diameter || 1;
  37630. var thickness = options.thickness || 0.5;
  37631. var tessellation = options.tessellation || 16;
  37632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37633. var stride = tessellation + 1;
  37634. for (var i = 0; i <= tessellation; i++) {
  37635. var u = i / tessellation;
  37636. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37637. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37638. for (var j = 0; j <= tessellation; j++) {
  37639. var v = 1 - j / tessellation;
  37640. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37641. var dx = Math.cos(innerAngle);
  37642. var dy = Math.sin(innerAngle);
  37643. // Create a vertex.
  37644. var normal = new BABYLON.Vector3(dx, dy, 0);
  37645. var position = normal.scale(thickness / 2);
  37646. var textureCoordinate = new BABYLON.Vector2(u, v);
  37647. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37648. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37649. positions.push(position.x, position.y, position.z);
  37650. normals.push(normal.x, normal.y, normal.z);
  37651. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37652. // And create indices for two triangles.
  37653. var nextI = (i + 1) % stride;
  37654. var nextJ = (j + 1) % stride;
  37655. indices.push(i * stride + j);
  37656. indices.push(i * stride + nextJ);
  37657. indices.push(nextI * stride + j);
  37658. indices.push(i * stride + nextJ);
  37659. indices.push(nextI * stride + nextJ);
  37660. indices.push(nextI * stride + j);
  37661. }
  37662. }
  37663. // Sides
  37664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37665. // Result
  37666. var vertexData = new VertexData();
  37667. vertexData.indices = indices;
  37668. vertexData.positions = positions;
  37669. vertexData.normals = normals;
  37670. vertexData.uvs = uvs;
  37671. return vertexData;
  37672. };
  37673. /**
  37674. * Creates the VertexData of the LineSystem
  37675. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37676. * - lines an array of lines, each line being an array of successive Vector3
  37677. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37678. * @returns the VertexData of the LineSystem
  37679. */
  37680. VertexData.CreateLineSystem = function (options) {
  37681. var indices = [];
  37682. var positions = [];
  37683. var lines = options.lines;
  37684. var colors = options.colors;
  37685. var vertexColors = [];
  37686. var idx = 0;
  37687. for (var l = 0; l < lines.length; l++) {
  37688. var points = lines[l];
  37689. for (var index = 0; index < points.length; index++) {
  37690. positions.push(points[index].x, points[index].y, points[index].z);
  37691. if (colors) {
  37692. var color = colors[l];
  37693. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37694. }
  37695. if (index > 0) {
  37696. indices.push(idx - 1);
  37697. indices.push(idx);
  37698. }
  37699. idx++;
  37700. }
  37701. }
  37702. var vertexData = new VertexData();
  37703. vertexData.indices = indices;
  37704. vertexData.positions = positions;
  37705. if (colors) {
  37706. vertexData.colors = vertexColors;
  37707. }
  37708. return vertexData;
  37709. };
  37710. /**
  37711. * Create the VertexData for a DashedLines
  37712. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37713. * - points an array successive Vector3
  37714. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37715. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37716. * - dashNb the intended total number of dashes, optional, default 200
  37717. * @returns the VertexData for the DashedLines
  37718. */
  37719. VertexData.CreateDashedLines = function (options) {
  37720. var dashSize = options.dashSize || 3;
  37721. var gapSize = options.gapSize || 1;
  37722. var dashNb = options.dashNb || 200;
  37723. var points = options.points;
  37724. var positions = new Array();
  37725. var indices = new Array();
  37726. var curvect = BABYLON.Vector3.Zero();
  37727. var lg = 0;
  37728. var nb = 0;
  37729. var shft = 0;
  37730. var dashshft = 0;
  37731. var curshft = 0;
  37732. var idx = 0;
  37733. var i = 0;
  37734. for (i = 0; i < points.length - 1; i++) {
  37735. points[i + 1].subtractToRef(points[i], curvect);
  37736. lg += curvect.length();
  37737. }
  37738. shft = lg / dashNb;
  37739. dashshft = dashSize * shft / (dashSize + gapSize);
  37740. for (i = 0; i < points.length - 1; i++) {
  37741. points[i + 1].subtractToRef(points[i], curvect);
  37742. nb = Math.floor(curvect.length() / shft);
  37743. curvect.normalize();
  37744. for (var j = 0; j < nb; j++) {
  37745. curshft = shft * j;
  37746. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37747. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37748. indices.push(idx, idx + 1);
  37749. idx += 2;
  37750. }
  37751. }
  37752. // Result
  37753. var vertexData = new VertexData();
  37754. vertexData.positions = positions;
  37755. vertexData.indices = indices;
  37756. return vertexData;
  37757. };
  37758. /**
  37759. * Creates the VertexData for a Ground
  37760. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37761. * - width the width (x direction) of the ground, optional, default 1
  37762. * - height the height (z direction) of the ground, optional, default 1
  37763. * - subdivisions the number of subdivisions per side, optional, default 1
  37764. * @returns the VertexData of the Ground
  37765. */
  37766. VertexData.CreateGround = function (options) {
  37767. var indices = [];
  37768. var positions = [];
  37769. var normals = [];
  37770. var uvs = [];
  37771. var row, col;
  37772. var width = options.width || 1;
  37773. var height = options.height || 1;
  37774. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37775. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37776. for (row = 0; row <= subdivisionsY; row++) {
  37777. for (col = 0; col <= subdivisionsX; col++) {
  37778. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37779. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37780. positions.push(position.x, position.y, position.z);
  37781. normals.push(normal.x, normal.y, normal.z);
  37782. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37783. }
  37784. }
  37785. for (row = 0; row < subdivisionsY; row++) {
  37786. for (col = 0; col < subdivisionsX; col++) {
  37787. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37788. indices.push(col + 1 + row * (subdivisionsX + 1));
  37789. indices.push(col + row * (subdivisionsX + 1));
  37790. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37791. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37792. indices.push(col + row * (subdivisionsX + 1));
  37793. }
  37794. }
  37795. // Result
  37796. var vertexData = new VertexData();
  37797. vertexData.indices = indices;
  37798. vertexData.positions = positions;
  37799. vertexData.normals = normals;
  37800. vertexData.uvs = uvs;
  37801. return vertexData;
  37802. };
  37803. /**
  37804. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37805. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37806. * * xmin the ground minimum X coordinate, optional, default -1
  37807. * * zmin the ground minimum Z coordinate, optional, default -1
  37808. * * xmax the ground maximum X coordinate, optional, default 1
  37809. * * zmax the ground maximum Z coordinate, optional, default 1
  37810. * * 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}
  37811. * * 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}
  37812. * @returns the VertexData of the TiledGround
  37813. */
  37814. VertexData.CreateTiledGround = function (options) {
  37815. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37816. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37817. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37818. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37819. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37820. var precision = options.precision || { w: 1, h: 1 };
  37821. var indices = new Array();
  37822. var positions = new Array();
  37823. var normals = new Array();
  37824. var uvs = new Array();
  37825. var row, col, tileRow, tileCol;
  37826. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37827. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37828. precision.w = (precision.w < 1) ? 1 : precision.w;
  37829. precision.h = (precision.h < 1) ? 1 : precision.h;
  37830. var tileSize = {
  37831. 'w': (xmax - xmin) / subdivisions.w,
  37832. 'h': (zmax - zmin) / subdivisions.h
  37833. };
  37834. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37835. // Indices
  37836. var base = positions.length / 3;
  37837. var rowLength = precision.w + 1;
  37838. for (row = 0; row < precision.h; row++) {
  37839. for (col = 0; col < precision.w; col++) {
  37840. var square = [
  37841. base + col + row * rowLength,
  37842. base + (col + 1) + row * rowLength,
  37843. base + (col + 1) + (row + 1) * rowLength,
  37844. base + col + (row + 1) * rowLength
  37845. ];
  37846. indices.push(square[1]);
  37847. indices.push(square[2]);
  37848. indices.push(square[3]);
  37849. indices.push(square[0]);
  37850. indices.push(square[1]);
  37851. indices.push(square[3]);
  37852. }
  37853. }
  37854. // Position, normals and uvs
  37855. var position = BABYLON.Vector3.Zero();
  37856. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37857. for (row = 0; row <= precision.h; row++) {
  37858. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37859. for (col = 0; col <= precision.w; col++) {
  37860. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37861. position.y = 0;
  37862. positions.push(position.x, position.y, position.z);
  37863. normals.push(normal.x, normal.y, normal.z);
  37864. uvs.push(col / precision.w, row / precision.h);
  37865. }
  37866. }
  37867. }
  37868. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37869. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37870. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37871. }
  37872. }
  37873. // Result
  37874. var vertexData = new VertexData();
  37875. vertexData.indices = indices;
  37876. vertexData.positions = positions;
  37877. vertexData.normals = normals;
  37878. vertexData.uvs = uvs;
  37879. return vertexData;
  37880. };
  37881. /**
  37882. * Creates the VertexData of the Ground designed from a heightmap
  37883. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37884. * * width the width (x direction) of the ground
  37885. * * height the height (z direction) of the ground
  37886. * * subdivisions the number of subdivisions per side
  37887. * * minHeight the minimum altitude on the ground, optional, default 0
  37888. * * maxHeight the maximum altitude on the ground, optional default 1
  37889. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37890. * * buffer the array holding the image color data
  37891. * * bufferWidth the width of image
  37892. * * bufferHeight the height of image
  37893. * @returns the VertexData of the Ground designed from a heightmap
  37894. */
  37895. VertexData.CreateGroundFromHeightMap = function (options) {
  37896. var indices = [];
  37897. var positions = [];
  37898. var normals = [];
  37899. var uvs = [];
  37900. var row, col;
  37901. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37902. // Vertices
  37903. for (row = 0; row <= options.subdivisions; row++) {
  37904. for (col = 0; col <= options.subdivisions; col++) {
  37905. 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));
  37906. // Compute height
  37907. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37908. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37909. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37910. var r = options.buffer[pos] / 255.0;
  37911. var g = options.buffer[pos + 1] / 255.0;
  37912. var b = options.buffer[pos + 2] / 255.0;
  37913. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37914. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37915. // Add vertex
  37916. positions.push(position.x, position.y, position.z);
  37917. normals.push(0, 0, 0);
  37918. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37919. }
  37920. }
  37921. // Indices
  37922. for (row = 0; row < options.subdivisions; row++) {
  37923. for (col = 0; col < options.subdivisions; col++) {
  37924. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37925. indices.push(col + 1 + row * (options.subdivisions + 1));
  37926. indices.push(col + row * (options.subdivisions + 1));
  37927. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37928. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37929. indices.push(col + row * (options.subdivisions + 1));
  37930. }
  37931. }
  37932. // Normals
  37933. VertexData.ComputeNormals(positions, indices, normals);
  37934. // Result
  37935. var vertexData = new VertexData();
  37936. vertexData.indices = indices;
  37937. vertexData.positions = positions;
  37938. vertexData.normals = normals;
  37939. vertexData.uvs = uvs;
  37940. return vertexData;
  37941. };
  37942. /**
  37943. * Creates the VertexData for a Plane
  37944. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37945. * * size sets the width and height of the plane to the value of size, optional default 1
  37946. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37947. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37948. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37949. * * 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)
  37950. * * 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)
  37951. * @returns the VertexData of the box
  37952. */
  37953. VertexData.CreatePlane = function (options) {
  37954. var indices = [];
  37955. var positions = [];
  37956. var normals = [];
  37957. var uvs = [];
  37958. var width = options.width || options.size || 1;
  37959. var height = options.height || options.size || 1;
  37960. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37961. // Vertices
  37962. var halfWidth = width / 2.0;
  37963. var halfHeight = height / 2.0;
  37964. positions.push(-halfWidth, -halfHeight, 0);
  37965. normals.push(0, 0, -1.0);
  37966. uvs.push(0.0, 0.0);
  37967. positions.push(halfWidth, -halfHeight, 0);
  37968. normals.push(0, 0, -1.0);
  37969. uvs.push(1.0, 0.0);
  37970. positions.push(halfWidth, halfHeight, 0);
  37971. normals.push(0, 0, -1.0);
  37972. uvs.push(1.0, 1.0);
  37973. positions.push(-halfWidth, halfHeight, 0);
  37974. normals.push(0, 0, -1.0);
  37975. uvs.push(0.0, 1.0);
  37976. // Indices
  37977. indices.push(0);
  37978. indices.push(1);
  37979. indices.push(2);
  37980. indices.push(0);
  37981. indices.push(2);
  37982. indices.push(3);
  37983. // Sides
  37984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37985. // Result
  37986. var vertexData = new VertexData();
  37987. vertexData.indices = indices;
  37988. vertexData.positions = positions;
  37989. vertexData.normals = normals;
  37990. vertexData.uvs = uvs;
  37991. return vertexData;
  37992. };
  37993. /**
  37994. * Creates the VertexData of the Disc or regular Polygon
  37995. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37996. * * radius the radius of the disc, optional default 0.5
  37997. * * tessellation the number of polygon sides, optional, default 64
  37998. * * 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
  37999. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38000. * * 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)
  38001. * * 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)
  38002. * @returns the VertexData of the box
  38003. */
  38004. VertexData.CreateDisc = function (options) {
  38005. var positions = new Array();
  38006. var indices = new Array();
  38007. var normals = new Array();
  38008. var uvs = new Array();
  38009. var radius = options.radius || 0.5;
  38010. var tessellation = options.tessellation || 64;
  38011. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38013. // positions and uvs
  38014. positions.push(0, 0, 0); // disc center first
  38015. uvs.push(0.5, 0.5);
  38016. var theta = Math.PI * 2 * arc;
  38017. var step = theta / tessellation;
  38018. for (var a = 0; a < theta; a += step) {
  38019. var x = Math.cos(a);
  38020. var y = Math.sin(a);
  38021. var u = (x + 1) / 2;
  38022. var v = (1 - y) / 2;
  38023. positions.push(radius * x, radius * y, 0);
  38024. uvs.push(u, v);
  38025. }
  38026. if (arc === 1) {
  38027. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38028. uvs.push(uvs[2], uvs[3]);
  38029. }
  38030. //indices
  38031. var vertexNb = positions.length / 3;
  38032. for (var i = 1; i < vertexNb - 1; i++) {
  38033. indices.push(i + 1, 0, i);
  38034. }
  38035. // result
  38036. VertexData.ComputeNormals(positions, indices, normals);
  38037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38038. var vertexData = new VertexData();
  38039. vertexData.indices = indices;
  38040. vertexData.positions = positions;
  38041. vertexData.normals = normals;
  38042. vertexData.uvs = uvs;
  38043. return vertexData;
  38044. };
  38045. /**
  38046. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38047. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38048. * @param polygon a mesh built from polygonTriangulation.build()
  38049. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38050. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38051. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38052. * @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)
  38053. * @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)
  38054. * @returns the VertexData of the Polygon
  38055. */
  38056. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38057. var faceUV = fUV || new Array(3);
  38058. var faceColors = fColors;
  38059. var colors = [];
  38060. // default face colors and UV if undefined
  38061. for (var f = 0; f < 3; f++) {
  38062. if (faceUV[f] === undefined) {
  38063. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38064. }
  38065. if (faceColors && faceColors[f] === undefined) {
  38066. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38067. }
  38068. }
  38069. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38070. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38071. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38072. var indices = polygon.getIndices();
  38073. // set face colours and textures
  38074. var idx = 0;
  38075. var face = 0;
  38076. for (var index = 0; index < normals.length; index += 3) {
  38077. //Edge Face no. 1
  38078. if (Math.abs(normals[index + 1]) < 0.001) {
  38079. face = 1;
  38080. }
  38081. //Top Face no. 0
  38082. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38083. face = 0;
  38084. }
  38085. //Bottom Face no. 2
  38086. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38087. face = 2;
  38088. }
  38089. idx = index / 3;
  38090. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38091. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38092. if (faceColors) {
  38093. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38094. }
  38095. }
  38096. // sides
  38097. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38098. // Result
  38099. var vertexData = new VertexData();
  38100. vertexData.indices = indices;
  38101. vertexData.positions = positions;
  38102. vertexData.normals = normals;
  38103. vertexData.uvs = uvs;
  38104. if (faceColors) {
  38105. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38106. vertexData.colors = totalColors;
  38107. }
  38108. return vertexData;
  38109. };
  38110. /**
  38111. * Creates the VertexData of the IcoSphere
  38112. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38113. * * radius the radius of the IcoSphere, optional default 1
  38114. * * radiusX allows stretching in the x direction, optional, default radius
  38115. * * radiusY allows stretching in the y direction, optional, default radius
  38116. * * radiusZ allows stretching in the z direction, optional, default radius
  38117. * * flat when true creates a flat shaded mesh, optional, default true
  38118. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38119. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38120. * * 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)
  38121. * * 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)
  38122. * @returns the VertexData of the IcoSphere
  38123. */
  38124. VertexData.CreateIcoSphere = function (options) {
  38125. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38126. var radius = options.radius || 1;
  38127. var flat = (options.flat === undefined) ? true : options.flat;
  38128. var subdivisions = options.subdivisions || 4;
  38129. var radiusX = options.radiusX || radius;
  38130. var radiusY = options.radiusY || radius;
  38131. var radiusZ = options.radiusZ || radius;
  38132. var t = (1 + Math.sqrt(5)) / 2;
  38133. // 12 vertex x,y,z
  38134. var ico_vertices = [
  38135. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38136. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38137. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38138. ];
  38139. // index of 3 vertex makes a face of icopshere
  38140. var ico_indices = [
  38141. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38142. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38143. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38144. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38145. ];
  38146. // vertex for uv have aliased position, not for UV
  38147. var vertices_unalias_id = [
  38148. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38149. // vertex alias
  38150. 0,
  38151. 2,
  38152. 3,
  38153. 3,
  38154. 3,
  38155. 4,
  38156. 7,
  38157. 8,
  38158. 9,
  38159. 9,
  38160. 10,
  38161. 11 // 23: B + 12
  38162. ];
  38163. // uv as integer step (not pixels !)
  38164. var ico_vertexuv = [
  38165. 5, 1, 3, 1, 6, 4, 0, 0,
  38166. 5, 3, 4, 2, 2, 2, 4, 0,
  38167. 2, 0, 1, 1, 6, 0, 6, 2,
  38168. // vertex alias (for same vertex on different faces)
  38169. 0, 4,
  38170. 3, 3,
  38171. 4, 4,
  38172. 3, 1,
  38173. 4, 2,
  38174. 4, 4,
  38175. 0, 2,
  38176. 1, 1,
  38177. 2, 2,
  38178. 3, 3,
  38179. 1, 3,
  38180. 2, 4 // 23: B + 12
  38181. ];
  38182. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38183. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38184. // First island of uv mapping
  38185. // v = 4h 3+ 2
  38186. // v = 3h 9+ 4
  38187. // v = 2h 9+ 5 B
  38188. // v = 1h 9 1 0
  38189. // v = 0h 3 8 7 A
  38190. // u = 0 1 2 3 4 5 6 *a
  38191. // Second island of uv mapping
  38192. // v = 4h 0+ B+ 4+
  38193. // v = 3h A+ 2+
  38194. // v = 2h 7+ 6 3+
  38195. // v = 1h 8+ 3+
  38196. // v = 0h
  38197. // u = 0 1 2 3 4 5 6 *a
  38198. // Face layout on texture UV mapping
  38199. // ============
  38200. // \ 4 /\ 16 / ======
  38201. // \ / \ / /\ 11 /
  38202. // \/ 7 \/ / \ /
  38203. // ======= / 10 \/
  38204. // /\ 17 /\ =======
  38205. // / \ / \ \ 15 /\
  38206. // / 8 \/ 12 \ \ / \
  38207. // ============ \/ 6 \
  38208. // \ 18 /\ ============
  38209. // \ / \ \ 5 /\ 0 /
  38210. // \/ 13 \ \ / \ /
  38211. // ======= \/ 1 \/
  38212. // =============
  38213. // /\ 19 /\ 2 /\
  38214. // / \ / \ / \
  38215. // / 14 \/ 9 \/ 3 \
  38216. // ===================
  38217. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38218. var ustep = 138 / 1024;
  38219. var vstep = 239 / 1024;
  38220. var uoffset = 60 / 1024;
  38221. var voffset = 26 / 1024;
  38222. // Second island should have margin, not to touch the first island
  38223. // avoid any borderline artefact in pixel rounding
  38224. var island_u_offset = -40 / 1024;
  38225. var island_v_offset = +20 / 1024;
  38226. // face is either island 0 or 1 :
  38227. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38228. var island = [
  38229. 0, 0, 0, 0, 1,
  38230. 0, 0, 1, 1, 0,
  38231. 0, 0, 1, 1, 0,
  38232. 0, 1, 1, 1, 0 // 15 - 19
  38233. ];
  38234. var indices = new Array();
  38235. var positions = new Array();
  38236. var normals = new Array();
  38237. var uvs = new Array();
  38238. var current_indice = 0;
  38239. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38240. var face_vertex_pos = new Array(3);
  38241. var face_vertex_uv = new Array(3);
  38242. var v012;
  38243. for (v012 = 0; v012 < 3; v012++) {
  38244. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38245. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38246. }
  38247. // create all with normals
  38248. for (var face = 0; face < 20; face++) {
  38249. // 3 vertex per face
  38250. for (v012 = 0; v012 < 3; v012++) {
  38251. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38252. var v_id = ico_indices[3 * face + v012];
  38253. // vertex have 3D position (x,y,z)
  38254. 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]);
  38255. // Normalize to get normal, then scale to radius
  38256. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38257. // uv Coordinates from vertex ID
  38258. 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);
  38259. }
  38260. // Subdivide the face (interpolate pos, norm, uv)
  38261. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38262. // - norm is linear interpolation of vertex corner normal
  38263. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38264. // - uv is linear interpolation
  38265. //
  38266. // Topology is as below for sub-divide by 2
  38267. // vertex shown as v0,v1,v2
  38268. // interp index is i1 to progress in range [v0,v1[
  38269. // interp index is i2 to progress in range [v0,v2[
  38270. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38271. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38272. //
  38273. //
  38274. // i2 v2
  38275. // ^ ^
  38276. // / / \
  38277. // / / \
  38278. // / / \
  38279. // / / (0,1) \
  38280. // / #---------\
  38281. // / / \ (0,0)'/ \
  38282. // / / \ / \
  38283. // / / \ / \
  38284. // / / (0,0) \ / (1,0) \
  38285. // / #---------#---------\
  38286. // v0 v1
  38287. //
  38288. // --------------------> i1
  38289. //
  38290. // interp of (i1,i2):
  38291. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38292. // along i1 : lerp(x0,x1, i1/(S-i2))
  38293. //
  38294. // centroid of triangle is needed to get help normal computation
  38295. // (c1,c2) are used for centroid location
  38296. var interp_vertex = function (i1, i2, c1, c2) {
  38297. // vertex is interpolated from
  38298. // - face_vertex_pos[0..2]
  38299. // - face_vertex_uv[0..2]
  38300. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38301. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38302. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38303. pos_interp.normalize();
  38304. var vertex_normal;
  38305. if (flat) {
  38306. // in flat mode, recalculate normal as face centroid normal
  38307. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38308. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38309. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38310. }
  38311. else {
  38312. // in smooth mode, recalculate normal from each single vertex position
  38313. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38314. }
  38315. // Vertex normal need correction due to X,Y,Z radius scaling
  38316. vertex_normal.x /= radiusX;
  38317. vertex_normal.y /= radiusY;
  38318. vertex_normal.z /= radiusZ;
  38319. vertex_normal.normalize();
  38320. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38321. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38322. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38323. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38324. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38325. uvs.push(uv_interp.x, uv_interp.y);
  38326. // push each vertex has member of a face
  38327. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38328. indices.push(current_indice);
  38329. current_indice++;
  38330. };
  38331. for (var i2 = 0; i2 < subdivisions; i2++) {
  38332. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38333. // face : (i1,i2) for /\ :
  38334. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38335. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38336. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38337. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38338. if (i1 + i2 + 1 < subdivisions) {
  38339. // face : (i1,i2)' for \/ :
  38340. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38341. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38342. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38343. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38344. }
  38345. }
  38346. }
  38347. }
  38348. // Sides
  38349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38350. // Result
  38351. var vertexData = new VertexData();
  38352. vertexData.indices = indices;
  38353. vertexData.positions = positions;
  38354. vertexData.normals = normals;
  38355. vertexData.uvs = uvs;
  38356. return vertexData;
  38357. };
  38358. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38359. /**
  38360. * Creates the VertexData for a Polyhedron
  38361. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38362. * * type provided types are:
  38363. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38364. * * 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)
  38365. * * size the size of the IcoSphere, optional default 1
  38366. * * sizeX allows stretching in the x direction, optional, default size
  38367. * * sizeY allows stretching in the y direction, optional, default size
  38368. * * sizeZ allows stretching in the z direction, optional, default size
  38369. * * 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
  38370. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38371. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38372. * * flat when true creates a flat shaded mesh, optional, default true
  38373. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38374. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38375. * * 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)
  38376. * * 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)
  38377. * @returns the VertexData of the Polyhedron
  38378. */
  38379. VertexData.CreatePolyhedron = function (options) {
  38380. // provided polyhedron types :
  38381. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38382. // 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)
  38383. var polyhedra = [];
  38384. 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]] };
  38385. 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]] };
  38386. polyhedra[2] = {
  38387. 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]],
  38388. 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]]
  38389. };
  38390. polyhedra[3] = {
  38391. 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]],
  38392. 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]]
  38393. };
  38394. polyhedra[4] = {
  38395. 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]],
  38396. 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]]
  38397. };
  38398. 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]] };
  38399. 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]] };
  38400. 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]] };
  38401. 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]] };
  38402. 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]] };
  38403. 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]] };
  38404. 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]] };
  38405. 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]] };
  38406. 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]] };
  38407. polyhedra[14] = {
  38408. 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]],
  38409. 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]]
  38410. };
  38411. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38412. var size = options.size;
  38413. var sizeX = options.sizeX || size || 1;
  38414. var sizeY = options.sizeY || size || 1;
  38415. var sizeZ = options.sizeZ || size || 1;
  38416. var data = options.custom || polyhedra[type];
  38417. var nbfaces = data.face.length;
  38418. var faceUV = options.faceUV || new Array(nbfaces);
  38419. var faceColors = options.faceColors;
  38420. var flat = (options.flat === undefined) ? true : options.flat;
  38421. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38422. var positions = new Array();
  38423. var indices = new Array();
  38424. var normals = new Array();
  38425. var uvs = new Array();
  38426. var colors = new Array();
  38427. var index = 0;
  38428. var faceIdx = 0; // face cursor in the array "indexes"
  38429. var indexes = new Array();
  38430. var i = 0;
  38431. var f = 0;
  38432. var u, v, ang, x, y, tmp;
  38433. // default face colors and UV if undefined
  38434. if (flat) {
  38435. for (f = 0; f < nbfaces; f++) {
  38436. if (faceColors && faceColors[f] === undefined) {
  38437. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38438. }
  38439. if (faceUV && faceUV[f] === undefined) {
  38440. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38441. }
  38442. }
  38443. }
  38444. if (!flat) {
  38445. for (i = 0; i < data.vertex.length; i++) {
  38446. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38447. uvs.push(0, 0);
  38448. }
  38449. for (f = 0; f < nbfaces; f++) {
  38450. for (i = 0; i < data.face[f].length - 2; i++) {
  38451. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38452. }
  38453. }
  38454. }
  38455. else {
  38456. for (f = 0; f < nbfaces; f++) {
  38457. var fl = data.face[f].length; // number of vertices of the current face
  38458. ang = 2 * Math.PI / fl;
  38459. x = 0.5 * Math.tan(ang / 2);
  38460. y = 0.5;
  38461. // positions, uvs, colors
  38462. for (i = 0; i < fl; i++) {
  38463. // positions
  38464. 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);
  38465. indexes.push(index);
  38466. index++;
  38467. // uvs
  38468. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38469. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38470. uvs.push(u, v);
  38471. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38472. y = x * Math.sin(ang) + y * Math.cos(ang);
  38473. x = tmp;
  38474. // colors
  38475. if (faceColors) {
  38476. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38477. }
  38478. }
  38479. // indices from indexes
  38480. for (i = 0; i < fl - 2; i++) {
  38481. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38482. }
  38483. faceIdx += fl;
  38484. }
  38485. }
  38486. VertexData.ComputeNormals(positions, indices, normals);
  38487. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38488. var vertexData = new VertexData();
  38489. vertexData.positions = positions;
  38490. vertexData.indices = indices;
  38491. vertexData.normals = normals;
  38492. vertexData.uvs = uvs;
  38493. if (faceColors && flat) {
  38494. vertexData.colors = colors;
  38495. }
  38496. return vertexData;
  38497. };
  38498. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38499. /**
  38500. * Creates the VertexData for a TorusKnot
  38501. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38502. * * radius the radius of the torus knot, optional, default 2
  38503. * * tube the thickness of the tube, optional, default 0.5
  38504. * * radialSegments the number of sides on each tube segments, optional, default 32
  38505. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38506. * * p the number of windings around the z axis, optional, default 2
  38507. * * q the number of windings around the x axis, optional, default 3
  38508. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38509. * * 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)
  38510. * * 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)
  38511. * @returns the VertexData of the Torus Knot
  38512. */
  38513. VertexData.CreateTorusKnot = function (options) {
  38514. var indices = new Array();
  38515. var positions = new Array();
  38516. var normals = new Array();
  38517. var uvs = new Array();
  38518. var radius = options.radius || 2;
  38519. var tube = options.tube || 0.5;
  38520. var radialSegments = options.radialSegments || 32;
  38521. var tubularSegments = options.tubularSegments || 32;
  38522. var p = options.p || 2;
  38523. var q = options.q || 3;
  38524. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38525. // Helper
  38526. var getPos = function (angle) {
  38527. var cu = Math.cos(angle);
  38528. var su = Math.sin(angle);
  38529. var quOverP = q / p * angle;
  38530. var cs = Math.cos(quOverP);
  38531. var tx = radius * (2 + cs) * 0.5 * cu;
  38532. var ty = radius * (2 + cs) * su * 0.5;
  38533. var tz = radius * Math.sin(quOverP) * 0.5;
  38534. return new BABYLON.Vector3(tx, ty, tz);
  38535. };
  38536. // Vertices
  38537. var i;
  38538. var j;
  38539. for (i = 0; i <= radialSegments; i++) {
  38540. var modI = i % radialSegments;
  38541. var u = modI / radialSegments * 2 * p * Math.PI;
  38542. var p1 = getPos(u);
  38543. var p2 = getPos(u + 0.01);
  38544. var tang = p2.subtract(p1);
  38545. var n = p2.add(p1);
  38546. var bitan = BABYLON.Vector3.Cross(tang, n);
  38547. n = BABYLON.Vector3.Cross(bitan, tang);
  38548. bitan.normalize();
  38549. n.normalize();
  38550. for (j = 0; j < tubularSegments; j++) {
  38551. var modJ = j % tubularSegments;
  38552. var v = modJ / tubularSegments * 2 * Math.PI;
  38553. var cx = -tube * Math.cos(v);
  38554. var cy = tube * Math.sin(v);
  38555. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38556. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38557. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38558. uvs.push(i / radialSegments);
  38559. uvs.push(j / tubularSegments);
  38560. }
  38561. }
  38562. for (i = 0; i < radialSegments; i++) {
  38563. for (j = 0; j < tubularSegments; j++) {
  38564. var jNext = (j + 1) % tubularSegments;
  38565. var a = i * tubularSegments + j;
  38566. var b = (i + 1) * tubularSegments + j;
  38567. var c = (i + 1) * tubularSegments + jNext;
  38568. var d = i * tubularSegments + jNext;
  38569. indices.push(d);
  38570. indices.push(b);
  38571. indices.push(a);
  38572. indices.push(d);
  38573. indices.push(c);
  38574. indices.push(b);
  38575. }
  38576. }
  38577. // Normals
  38578. VertexData.ComputeNormals(positions, indices, normals);
  38579. // Sides
  38580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38581. // Result
  38582. var vertexData = new VertexData();
  38583. vertexData.indices = indices;
  38584. vertexData.positions = positions;
  38585. vertexData.normals = normals;
  38586. vertexData.uvs = uvs;
  38587. return vertexData;
  38588. };
  38589. // Tools
  38590. /**
  38591. * Compute normals for given positions and indices
  38592. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38593. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38594. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38595. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38596. * * facetNormals : optional array of facet normals (vector3)
  38597. * * facetPositions : optional array of facet positions (vector3)
  38598. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38599. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38600. * * bInfo : optional bounding info, required for facetPartitioning computation
  38601. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38602. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38603. * * useRightHandedSystem: optional boolean to for right handed system computation
  38604. * * depthSort : optional boolean to enable the facet depth sort computation
  38605. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38606. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38607. */
  38608. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38609. // temporary scalar variables
  38610. var index = 0; // facet index
  38611. var p1p2x = 0.0; // p1p2 vector x coordinate
  38612. var p1p2y = 0.0; // p1p2 vector y coordinate
  38613. var p1p2z = 0.0; // p1p2 vector z coordinate
  38614. var p3p2x = 0.0; // p3p2 vector x coordinate
  38615. var p3p2y = 0.0; // p3p2 vector y coordinate
  38616. var p3p2z = 0.0; // p3p2 vector z coordinate
  38617. var faceNormalx = 0.0; // facet normal x coordinate
  38618. var faceNormaly = 0.0; // facet normal y coordinate
  38619. var faceNormalz = 0.0; // facet normal z coordinate
  38620. var length = 0.0; // facet normal length before normalization
  38621. var v1x = 0; // vector1 x index in the positions array
  38622. var v1y = 0; // vector1 y index in the positions array
  38623. var v1z = 0; // vector1 z index in the positions array
  38624. var v2x = 0; // vector2 x index in the positions array
  38625. var v2y = 0; // vector2 y index in the positions array
  38626. var v2z = 0; // vector2 z index in the positions array
  38627. var v3x = 0; // vector3 x index in the positions array
  38628. var v3y = 0; // vector3 y index in the positions array
  38629. var v3z = 0; // vector3 z index in the positions array
  38630. var computeFacetNormals = false;
  38631. var computeFacetPositions = false;
  38632. var computeFacetPartitioning = false;
  38633. var computeDepthSort = false;
  38634. var faceNormalSign = 1;
  38635. var ratio = 0;
  38636. var distanceTo = null;
  38637. if (options) {
  38638. computeFacetNormals = (options.facetNormals) ? true : false;
  38639. computeFacetPositions = (options.facetPositions) ? true : false;
  38640. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38641. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38642. ratio = options.ratio || 0;
  38643. computeDepthSort = (options.depthSort) ? true : false;
  38644. distanceTo = (options.distanceTo);
  38645. if (computeDepthSort) {
  38646. if (distanceTo === undefined) {
  38647. distanceTo = BABYLON.Vector3.Zero();
  38648. }
  38649. var depthSortedFacets = options.depthSortedFacets;
  38650. }
  38651. }
  38652. // facetPartitioning reinit if needed
  38653. var xSubRatio = 0;
  38654. var ySubRatio = 0;
  38655. var zSubRatio = 0;
  38656. var subSq = 0;
  38657. if (computeFacetPartitioning && options && options.bbSize) {
  38658. var ox = 0; // X partitioning index for facet position
  38659. var oy = 0; // Y partinioning index for facet position
  38660. var oz = 0; // Z partinioning index for facet position
  38661. var b1x = 0; // X partitioning index for facet v1 vertex
  38662. var b1y = 0; // Y partitioning index for facet v1 vertex
  38663. var b1z = 0; // z partitioning index for facet v1 vertex
  38664. var b2x = 0; // X partitioning index for facet v2 vertex
  38665. var b2y = 0; // Y partitioning index for facet v2 vertex
  38666. var b2z = 0; // Z partitioning index for facet v2 vertex
  38667. var b3x = 0; // X partitioning index for facet v3 vertex
  38668. var b3y = 0; // Y partitioning index for facet v3 vertex
  38669. var b3z = 0; // Z partitioning index for facet v3 vertex
  38670. var block_idx_o = 0; // facet barycenter block index
  38671. var block_idx_v1 = 0; // v1 vertex block index
  38672. var block_idx_v2 = 0; // v2 vertex block index
  38673. var block_idx_v3 = 0; // v3 vertex block index
  38674. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38675. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38676. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38677. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38678. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38679. subSq = options.subDiv.max * options.subDiv.max;
  38680. options.facetPartitioning.length = 0;
  38681. }
  38682. // reset the normals
  38683. for (index = 0; index < positions.length; index++) {
  38684. normals[index] = 0.0;
  38685. }
  38686. // Loop : 1 indice triplet = 1 facet
  38687. var nbFaces = (indices.length / 3) | 0;
  38688. for (index = 0; index < nbFaces; index++) {
  38689. // get the indexes of the coordinates of each vertex of the facet
  38690. v1x = indices[index * 3] * 3;
  38691. v1y = v1x + 1;
  38692. v1z = v1x + 2;
  38693. v2x = indices[index * 3 + 1] * 3;
  38694. v2y = v2x + 1;
  38695. v2z = v2x + 2;
  38696. v3x = indices[index * 3 + 2] * 3;
  38697. v3y = v3x + 1;
  38698. v3z = v3x + 2;
  38699. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38700. p1p2y = positions[v1y] - positions[v2y];
  38701. p1p2z = positions[v1z] - positions[v2z];
  38702. p3p2x = positions[v3x] - positions[v2x];
  38703. p3p2y = positions[v3y] - positions[v2y];
  38704. p3p2z = positions[v3z] - positions[v2z];
  38705. // compute the face normal with the cross product
  38706. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38707. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38708. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38709. // normalize this normal and store it in the array facetData
  38710. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38711. length = (length === 0) ? 1.0 : length;
  38712. faceNormalx /= length;
  38713. faceNormaly /= length;
  38714. faceNormalz /= length;
  38715. if (computeFacetNormals && options) {
  38716. options.facetNormals[index].x = faceNormalx;
  38717. options.facetNormals[index].y = faceNormaly;
  38718. options.facetNormals[index].z = faceNormalz;
  38719. }
  38720. if (computeFacetPositions && options) {
  38721. // compute and the facet barycenter coordinates in the array facetPositions
  38722. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38723. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38724. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38725. }
  38726. if (computeFacetPartitioning && options) {
  38727. // store the facet indexes in arrays in the main facetPartitioning array :
  38728. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38729. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38730. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38731. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38732. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38733. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38734. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38735. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38736. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38737. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38738. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38739. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38740. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38741. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38742. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38743. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38744. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38745. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38746. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38747. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38748. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38749. // push each facet index in each block containing the vertex
  38750. options.facetPartitioning[block_idx_v1].push(index);
  38751. if (block_idx_v2 != block_idx_v1) {
  38752. options.facetPartitioning[block_idx_v2].push(index);
  38753. }
  38754. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38755. options.facetPartitioning[block_idx_v3].push(index);
  38756. }
  38757. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38758. options.facetPartitioning[block_idx_o].push(index);
  38759. }
  38760. }
  38761. if (computeDepthSort && options && options.facetPositions) {
  38762. var dsf = depthSortedFacets[index];
  38763. dsf.ind = index * 3;
  38764. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38765. }
  38766. // compute the normals anyway
  38767. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38768. normals[v1y] += faceNormaly;
  38769. normals[v1z] += faceNormalz;
  38770. normals[v2x] += faceNormalx;
  38771. normals[v2y] += faceNormaly;
  38772. normals[v2z] += faceNormalz;
  38773. normals[v3x] += faceNormalx;
  38774. normals[v3y] += faceNormaly;
  38775. normals[v3z] += faceNormalz;
  38776. }
  38777. // last normalization of each normal
  38778. for (index = 0; index < normals.length / 3; index++) {
  38779. faceNormalx = normals[index * 3];
  38780. faceNormaly = normals[index * 3 + 1];
  38781. faceNormalz = normals[index * 3 + 2];
  38782. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38783. length = (length === 0) ? 1.0 : length;
  38784. faceNormalx /= length;
  38785. faceNormaly /= length;
  38786. faceNormalz /= length;
  38787. normals[index * 3] = faceNormalx;
  38788. normals[index * 3 + 1] = faceNormaly;
  38789. normals[index * 3 + 2] = faceNormalz;
  38790. }
  38791. };
  38792. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38793. var li = indices.length;
  38794. var ln = normals.length;
  38795. var i;
  38796. var n;
  38797. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38798. switch (sideOrientation) {
  38799. case BABYLON.Mesh.FRONTSIDE:
  38800. // nothing changed
  38801. break;
  38802. case BABYLON.Mesh.BACKSIDE:
  38803. var tmp;
  38804. // indices
  38805. for (i = 0; i < li; i += 3) {
  38806. tmp = indices[i];
  38807. indices[i] = indices[i + 2];
  38808. indices[i + 2] = tmp;
  38809. }
  38810. // normals
  38811. for (n = 0; n < ln; n++) {
  38812. normals[n] = -normals[n];
  38813. }
  38814. break;
  38815. case BABYLON.Mesh.DOUBLESIDE:
  38816. // positions
  38817. var lp = positions.length;
  38818. var l = lp / 3;
  38819. for (var p = 0; p < lp; p++) {
  38820. positions[lp + p] = positions[p];
  38821. }
  38822. // indices
  38823. for (i = 0; i < li; i += 3) {
  38824. indices[i + li] = indices[i + 2] + l;
  38825. indices[i + 1 + li] = indices[i + 1] + l;
  38826. indices[i + 2 + li] = indices[i] + l;
  38827. }
  38828. // normals
  38829. for (n = 0; n < ln; n++) {
  38830. normals[ln + n] = -normals[n];
  38831. }
  38832. // uvs
  38833. var lu = uvs.length;
  38834. var u = 0;
  38835. for (u = 0; u < lu; u++) {
  38836. uvs[u + lu] = uvs[u];
  38837. }
  38838. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38839. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38840. u = 0;
  38841. for (i = 0; i < lu / 2; i++) {
  38842. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38843. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38844. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38845. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38846. u += 2;
  38847. }
  38848. break;
  38849. }
  38850. };
  38851. /**
  38852. * Applies VertexData created from the imported parameters to the geometry
  38853. * @param parsedVertexData the parsed data from an imported file
  38854. * @param geometry the geometry to apply the VertexData to
  38855. */
  38856. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38857. var vertexData = new VertexData();
  38858. // positions
  38859. var positions = parsedVertexData.positions;
  38860. if (positions) {
  38861. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38862. }
  38863. // normals
  38864. var normals = parsedVertexData.normals;
  38865. if (normals) {
  38866. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38867. }
  38868. // tangents
  38869. var tangents = parsedVertexData.tangents;
  38870. if (tangents) {
  38871. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38872. }
  38873. // uvs
  38874. var uvs = parsedVertexData.uvs;
  38875. if (uvs) {
  38876. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38877. }
  38878. // uv2s
  38879. var uv2s = parsedVertexData.uv2s;
  38880. if (uv2s) {
  38881. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38882. }
  38883. // uv3s
  38884. var uv3s = parsedVertexData.uv3s;
  38885. if (uv3s) {
  38886. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38887. }
  38888. // uv4s
  38889. var uv4s = parsedVertexData.uv4s;
  38890. if (uv4s) {
  38891. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38892. }
  38893. // uv5s
  38894. var uv5s = parsedVertexData.uv5s;
  38895. if (uv5s) {
  38896. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38897. }
  38898. // uv6s
  38899. var uv6s = parsedVertexData.uv6s;
  38900. if (uv6s) {
  38901. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38902. }
  38903. // colors
  38904. var colors = parsedVertexData.colors;
  38905. if (colors) {
  38906. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38907. }
  38908. // matricesIndices
  38909. var matricesIndices = parsedVertexData.matricesIndices;
  38910. if (matricesIndices) {
  38911. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38912. }
  38913. // matricesWeights
  38914. var matricesWeights = parsedVertexData.matricesWeights;
  38915. if (matricesWeights) {
  38916. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38917. }
  38918. // indices
  38919. var indices = parsedVertexData.indices;
  38920. if (indices) {
  38921. vertexData.indices = indices;
  38922. }
  38923. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38924. };
  38925. return VertexData;
  38926. }());
  38927. BABYLON.VertexData = VertexData;
  38928. })(BABYLON || (BABYLON = {}));
  38929. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38930. var BABYLON;
  38931. (function (BABYLON) {
  38932. /**
  38933. * Class used to store geometry data (vertex buffers + index buffer)
  38934. */
  38935. var Geometry = /** @class */ (function () {
  38936. /**
  38937. * Creates a new geometry
  38938. * @param id defines the unique ID
  38939. * @param scene defines the hosting scene
  38940. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38941. * @param updatable defines if geometry must be updatable (false by default)
  38942. * @param mesh defines the mesh that will be associated with the geometry
  38943. */
  38944. function Geometry(id, scene, vertexData, updatable, mesh) {
  38945. if (updatable === void 0) { updatable = false; }
  38946. if (mesh === void 0) { mesh = null; }
  38947. /**
  38948. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38949. */
  38950. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38951. this._totalVertices = 0;
  38952. this._isDisposed = false;
  38953. this._indexBufferIsUpdatable = false;
  38954. this.id = id;
  38955. this._engine = scene.getEngine();
  38956. this._meshes = [];
  38957. this._scene = scene;
  38958. //Init vertex buffer cache
  38959. this._vertexBuffers = {};
  38960. this._indices = [];
  38961. this._updatable = updatable;
  38962. // vertexData
  38963. if (vertexData) {
  38964. this.setAllVerticesData(vertexData, updatable);
  38965. }
  38966. else {
  38967. this._totalVertices = 0;
  38968. this._indices = [];
  38969. }
  38970. if (this._engine.getCaps().vertexArrayObject) {
  38971. this._vertexArrayObjects = {};
  38972. }
  38973. // applyToMesh
  38974. if (mesh) {
  38975. if (mesh.getClassName() === "LinesMesh") {
  38976. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38977. this._updateExtend();
  38978. }
  38979. this.applyToMesh(mesh);
  38980. mesh.computeWorldMatrix(true);
  38981. }
  38982. }
  38983. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38984. /**
  38985. * 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
  38986. */
  38987. get: function () {
  38988. return this._boundingBias;
  38989. },
  38990. /**
  38991. * 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
  38992. */
  38993. set: function (value) {
  38994. if (this._boundingBias && this._boundingBias.equals(value)) {
  38995. return;
  38996. }
  38997. this._boundingBias = value.clone();
  38998. this._updateBoundingInfo(true, null);
  38999. },
  39000. enumerable: true,
  39001. configurable: true
  39002. });
  39003. /**
  39004. * Static function used to attach a new empty geometry to a mesh
  39005. * @param mesh defines the mesh to attach the geometry to
  39006. * @returns the new {BABYLON.Geometry}
  39007. */
  39008. Geometry.CreateGeometryForMesh = function (mesh) {
  39009. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39010. geometry.applyToMesh(mesh);
  39011. return geometry;
  39012. };
  39013. Object.defineProperty(Geometry.prototype, "extend", {
  39014. /**
  39015. * Gets the current extend of the geometry
  39016. */
  39017. get: function () {
  39018. return this._extend;
  39019. },
  39020. enumerable: true,
  39021. configurable: true
  39022. });
  39023. /**
  39024. * Gets the hosting scene
  39025. * @returns the hosting {BABYLON.Scene}
  39026. */
  39027. Geometry.prototype.getScene = function () {
  39028. return this._scene;
  39029. };
  39030. /**
  39031. * Gets the hosting engine
  39032. * @returns the hosting {BABYLON.Engine}
  39033. */
  39034. Geometry.prototype.getEngine = function () {
  39035. return this._engine;
  39036. };
  39037. /**
  39038. * Defines if the geometry is ready to use
  39039. * @returns true if the geometry is ready to be used
  39040. */
  39041. Geometry.prototype.isReady = function () {
  39042. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39043. };
  39044. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39045. /**
  39046. * Gets a value indicating that the geometry should not be serialized
  39047. */
  39048. get: function () {
  39049. for (var index = 0; index < this._meshes.length; index++) {
  39050. if (!this._meshes[index].doNotSerialize) {
  39051. return false;
  39052. }
  39053. }
  39054. return true;
  39055. },
  39056. enumerable: true,
  39057. configurable: true
  39058. });
  39059. /** @hidden */
  39060. Geometry.prototype._rebuild = function () {
  39061. if (this._vertexArrayObjects) {
  39062. this._vertexArrayObjects = {};
  39063. }
  39064. // Index buffer
  39065. if (this._meshes.length !== 0 && this._indices) {
  39066. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39067. }
  39068. // Vertex buffers
  39069. for (var key in this._vertexBuffers) {
  39070. var vertexBuffer = this._vertexBuffers[key];
  39071. vertexBuffer._rebuild();
  39072. }
  39073. };
  39074. /**
  39075. * Affects all gemetry data in one call
  39076. * @param vertexData defines the geometry data
  39077. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39078. */
  39079. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39080. vertexData.applyToGeometry(this, updatable);
  39081. this.notifyUpdate();
  39082. };
  39083. /**
  39084. * Set specific vertex data
  39085. * @param kind defines the data kind (Position, normal, etc...)
  39086. * @param data defines the vertex data to use
  39087. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39088. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39089. */
  39090. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39091. if (updatable === void 0) { updatable = false; }
  39092. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39093. this.setVerticesBuffer(buffer);
  39094. };
  39095. /**
  39096. * Removes a specific vertex data
  39097. * @param kind defines the data kind (Position, normal, etc...)
  39098. */
  39099. Geometry.prototype.removeVerticesData = function (kind) {
  39100. if (this._vertexBuffers[kind]) {
  39101. this._vertexBuffers[kind].dispose();
  39102. delete this._vertexBuffers[kind];
  39103. }
  39104. };
  39105. /**
  39106. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39107. * @param buffer defines the vertex buffer to use
  39108. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39109. */
  39110. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39111. if (totalVertices === void 0) { totalVertices = null; }
  39112. var kind = buffer.getKind();
  39113. if (this._vertexBuffers[kind]) {
  39114. this._vertexBuffers[kind].dispose();
  39115. }
  39116. this._vertexBuffers[kind] = buffer;
  39117. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39118. var data = buffer.getData();
  39119. if (totalVertices != null) {
  39120. this._totalVertices = totalVertices;
  39121. }
  39122. else {
  39123. if (data != null) {
  39124. this._totalVertices = data.length / (buffer.byteStride / 4);
  39125. }
  39126. }
  39127. this._updateExtend(data);
  39128. this._resetPointsArrayCache();
  39129. var meshes = this._meshes;
  39130. var numOfMeshes = meshes.length;
  39131. for (var index = 0; index < numOfMeshes; index++) {
  39132. var mesh = meshes[index];
  39133. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39134. mesh._createGlobalSubMesh(false);
  39135. mesh.computeWorldMatrix(true);
  39136. }
  39137. }
  39138. this.notifyUpdate(kind);
  39139. if (this._vertexArrayObjects) {
  39140. this._disposeVertexArrayObjects();
  39141. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39142. }
  39143. };
  39144. /**
  39145. * Update a specific vertex buffer
  39146. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39147. * It will do nothing if the buffer is not updatable
  39148. * @param kind defines the data kind (Position, normal, etc...)
  39149. * @param data defines the data to use
  39150. * @param offset defines the offset in the target buffer where to store the data
  39151. * @param useBytes set to true if the offset is in bytes
  39152. */
  39153. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39154. if (useBytes === void 0) { useBytes = false; }
  39155. var vertexBuffer = this.getVertexBuffer(kind);
  39156. if (!vertexBuffer) {
  39157. return;
  39158. }
  39159. vertexBuffer.updateDirectly(data, offset, useBytes);
  39160. this.notifyUpdate(kind);
  39161. };
  39162. /**
  39163. * Update a specific vertex buffer
  39164. * This function will create a new buffer if the current one is not updatable
  39165. * @param kind defines the data kind (Position, normal, etc...)
  39166. * @param data defines the data to use
  39167. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39168. */
  39169. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39170. if (updateExtends === void 0) { updateExtends = false; }
  39171. var vertexBuffer = this.getVertexBuffer(kind);
  39172. if (!vertexBuffer) {
  39173. return;
  39174. }
  39175. vertexBuffer.update(data);
  39176. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39177. this._updateBoundingInfo(updateExtends, data);
  39178. }
  39179. this.notifyUpdate(kind);
  39180. };
  39181. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39182. if (updateExtends) {
  39183. this._updateExtend(data);
  39184. }
  39185. var meshes = this._meshes;
  39186. var numOfMeshes = meshes.length;
  39187. this._resetPointsArrayCache();
  39188. for (var index = 0; index < numOfMeshes; index++) {
  39189. var mesh = meshes[index];
  39190. if (updateExtends) {
  39191. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39192. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39193. var subMesh = mesh.subMeshes[subIndex];
  39194. subMesh.refreshBoundingInfo();
  39195. }
  39196. }
  39197. }
  39198. };
  39199. /** @hidden */
  39200. Geometry.prototype._bind = function (effect, indexToBind) {
  39201. if (!effect) {
  39202. return;
  39203. }
  39204. if (indexToBind === undefined) {
  39205. indexToBind = this._indexBuffer;
  39206. }
  39207. var vbs = this.getVertexBuffers();
  39208. if (!vbs) {
  39209. return;
  39210. }
  39211. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39212. this._engine.bindBuffers(vbs, indexToBind, effect);
  39213. return;
  39214. }
  39215. // Using VAO
  39216. if (!this._vertexArrayObjects[effect.key]) {
  39217. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39218. }
  39219. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39220. };
  39221. /**
  39222. * Gets total number of vertices
  39223. * @returns the total number of vertices
  39224. */
  39225. Geometry.prototype.getTotalVertices = function () {
  39226. if (!this.isReady()) {
  39227. return 0;
  39228. }
  39229. return this._totalVertices;
  39230. };
  39231. /**
  39232. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39233. * @param kind defines the data kind (Position, normal, etc...)
  39234. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39235. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39236. * @returns a float array containing vertex data
  39237. */
  39238. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39239. var vertexBuffer = this.getVertexBuffer(kind);
  39240. if (!vertexBuffer) {
  39241. return null;
  39242. }
  39243. var data = vertexBuffer.getData();
  39244. if (!data) {
  39245. return null;
  39246. }
  39247. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39248. var count = this._totalVertices * vertexBuffer.getSize();
  39249. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39250. var copy_1 = new Array(count);
  39251. vertexBuffer.forEach(count, function (value, index) {
  39252. copy_1[index] = value;
  39253. });
  39254. return copy_1;
  39255. }
  39256. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39257. if (data instanceof Array) {
  39258. var offset = vertexBuffer.byteOffset / 4;
  39259. return BABYLON.Tools.Slice(data, offset, offset + count);
  39260. }
  39261. else if (data instanceof ArrayBuffer) {
  39262. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39263. }
  39264. else {
  39265. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39266. }
  39267. }
  39268. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39269. return BABYLON.Tools.Slice(data);
  39270. }
  39271. return data;
  39272. };
  39273. /**
  39274. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39275. * @param kind defines the data kind (Position, normal, etc...)
  39276. * @returns true if the vertex buffer with the specified kind is updatable
  39277. */
  39278. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39279. var vb = this._vertexBuffers[kind];
  39280. if (!vb) {
  39281. return false;
  39282. }
  39283. return vb.isUpdatable();
  39284. };
  39285. /**
  39286. * Gets a specific vertex buffer
  39287. * @param kind defines the data kind (Position, normal, etc...)
  39288. * @returns a {BABYLON.VertexBuffer}
  39289. */
  39290. Geometry.prototype.getVertexBuffer = function (kind) {
  39291. if (!this.isReady()) {
  39292. return null;
  39293. }
  39294. return this._vertexBuffers[kind];
  39295. };
  39296. /**
  39297. * Returns all vertex buffers
  39298. * @return an object holding all vertex buffers indexed by kind
  39299. */
  39300. Geometry.prototype.getVertexBuffers = function () {
  39301. if (!this.isReady()) {
  39302. return null;
  39303. }
  39304. return this._vertexBuffers;
  39305. };
  39306. /**
  39307. * Gets a boolean indicating if specific vertex buffer is present
  39308. * @param kind defines the data kind (Position, normal, etc...)
  39309. * @returns true if data is present
  39310. */
  39311. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39312. if (!this._vertexBuffers) {
  39313. if (this._delayInfo) {
  39314. return this._delayInfo.indexOf(kind) !== -1;
  39315. }
  39316. return false;
  39317. }
  39318. return this._vertexBuffers[kind] !== undefined;
  39319. };
  39320. /**
  39321. * Gets a list of all attached data kinds (Position, normal, etc...)
  39322. * @returns a list of string containing all kinds
  39323. */
  39324. Geometry.prototype.getVerticesDataKinds = function () {
  39325. var result = [];
  39326. var kind;
  39327. if (!this._vertexBuffers && this._delayInfo) {
  39328. for (kind in this._delayInfo) {
  39329. result.push(kind);
  39330. }
  39331. }
  39332. else {
  39333. for (kind in this._vertexBuffers) {
  39334. result.push(kind);
  39335. }
  39336. }
  39337. return result;
  39338. };
  39339. /**
  39340. * Update index buffer
  39341. * @param indices defines the indices to store in the index buffer
  39342. * @param offset defines the offset in the target buffer where to store the data
  39343. */
  39344. Geometry.prototype.updateIndices = function (indices, offset) {
  39345. if (!this._indexBuffer) {
  39346. return;
  39347. }
  39348. if (!this._indexBufferIsUpdatable) {
  39349. this.setIndices(indices, null, true);
  39350. }
  39351. else {
  39352. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39353. }
  39354. };
  39355. /**
  39356. * Creates a new index buffer
  39357. * @param indices defines the indices to store in the index buffer
  39358. * @param totalVertices defines the total number of vertices (could be null)
  39359. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39360. */
  39361. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39362. if (totalVertices === void 0) { totalVertices = null; }
  39363. if (updatable === void 0) { updatable = false; }
  39364. if (this._indexBuffer) {
  39365. this._engine._releaseBuffer(this._indexBuffer);
  39366. }
  39367. this._disposeVertexArrayObjects();
  39368. this._indices = indices;
  39369. this._indexBufferIsUpdatable = updatable;
  39370. if (this._meshes.length !== 0 && this._indices) {
  39371. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39372. }
  39373. if (totalVertices != undefined) { // including null and undefined
  39374. this._totalVertices = totalVertices;
  39375. }
  39376. var meshes = this._meshes;
  39377. var numOfMeshes = meshes.length;
  39378. for (var index = 0; index < numOfMeshes; index++) {
  39379. meshes[index]._createGlobalSubMesh(true);
  39380. }
  39381. this.notifyUpdate();
  39382. };
  39383. /**
  39384. * Return the total number of indices
  39385. * @returns the total number of indices
  39386. */
  39387. Geometry.prototype.getTotalIndices = function () {
  39388. if (!this.isReady()) {
  39389. return 0;
  39390. }
  39391. return this._indices.length;
  39392. };
  39393. /**
  39394. * Gets the index buffer array
  39395. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39396. * @returns the index buffer array
  39397. */
  39398. Geometry.prototype.getIndices = function (copyWhenShared) {
  39399. if (!this.isReady()) {
  39400. return null;
  39401. }
  39402. var orig = this._indices;
  39403. if (!copyWhenShared || this._meshes.length === 1) {
  39404. return orig;
  39405. }
  39406. else {
  39407. var len = orig.length;
  39408. var copy = [];
  39409. for (var i = 0; i < len; i++) {
  39410. copy.push(orig[i]);
  39411. }
  39412. return copy;
  39413. }
  39414. };
  39415. /**
  39416. * Gets the index buffer
  39417. * @return the index buffer
  39418. */
  39419. Geometry.prototype.getIndexBuffer = function () {
  39420. if (!this.isReady()) {
  39421. return null;
  39422. }
  39423. return this._indexBuffer;
  39424. };
  39425. /** @hidden */
  39426. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39427. if (effect === void 0) { effect = null; }
  39428. if (!effect || !this._vertexArrayObjects) {
  39429. return;
  39430. }
  39431. if (this._vertexArrayObjects[effect.key]) {
  39432. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39433. delete this._vertexArrayObjects[effect.key];
  39434. }
  39435. };
  39436. /**
  39437. * Release the associated resources for a specific mesh
  39438. * @param mesh defines the source mesh
  39439. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39440. */
  39441. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39442. var meshes = this._meshes;
  39443. var index = meshes.indexOf(mesh);
  39444. if (index === -1) {
  39445. return;
  39446. }
  39447. meshes.splice(index, 1);
  39448. mesh._geometry = null;
  39449. if (meshes.length === 0 && shouldDispose) {
  39450. this.dispose();
  39451. }
  39452. };
  39453. /**
  39454. * Apply current geometry to a given mesh
  39455. * @param mesh defines the mesh to apply geometry to
  39456. */
  39457. Geometry.prototype.applyToMesh = function (mesh) {
  39458. if (mesh._geometry === this) {
  39459. return;
  39460. }
  39461. var previousGeometry = mesh._geometry;
  39462. if (previousGeometry) {
  39463. previousGeometry.releaseForMesh(mesh);
  39464. }
  39465. var meshes = this._meshes;
  39466. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39467. mesh._geometry = this;
  39468. this._scene.pushGeometry(this);
  39469. meshes.push(mesh);
  39470. if (this.isReady()) {
  39471. this._applyToMesh(mesh);
  39472. }
  39473. else {
  39474. mesh._boundingInfo = this._boundingInfo;
  39475. }
  39476. };
  39477. Geometry.prototype._updateExtend = function (data) {
  39478. if (data === void 0) { data = null; }
  39479. if (!data) {
  39480. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39481. }
  39482. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39483. };
  39484. Geometry.prototype._applyToMesh = function (mesh) {
  39485. var numOfMeshes = this._meshes.length;
  39486. // vertexBuffers
  39487. for (var kind in this._vertexBuffers) {
  39488. if (numOfMeshes === 1) {
  39489. this._vertexBuffers[kind].create();
  39490. }
  39491. var buffer = this._vertexBuffers[kind].getBuffer();
  39492. if (buffer)
  39493. buffer.references = numOfMeshes;
  39494. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39495. if (!this._extend) {
  39496. this._updateExtend();
  39497. }
  39498. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39499. mesh._createGlobalSubMesh(false);
  39500. //bounding info was just created again, world matrix should be applied again.
  39501. mesh._updateBoundingInfo();
  39502. }
  39503. }
  39504. // indexBuffer
  39505. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39506. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39507. }
  39508. if (this._indexBuffer) {
  39509. this._indexBuffer.references = numOfMeshes;
  39510. }
  39511. };
  39512. Geometry.prototype.notifyUpdate = function (kind) {
  39513. if (this.onGeometryUpdated) {
  39514. this.onGeometryUpdated(this, kind);
  39515. }
  39516. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39517. var mesh = _a[_i];
  39518. mesh._markSubMeshesAsAttributesDirty();
  39519. }
  39520. };
  39521. /**
  39522. * Load the geometry if it was flagged as delay loaded
  39523. * @param scene defines the hosting scene
  39524. * @param onLoaded defines a callback called when the geometry is loaded
  39525. */
  39526. Geometry.prototype.load = function (scene, onLoaded) {
  39527. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39528. return;
  39529. }
  39530. if (this.isReady()) {
  39531. if (onLoaded) {
  39532. onLoaded();
  39533. }
  39534. return;
  39535. }
  39536. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39537. this._queueLoad(scene, onLoaded);
  39538. };
  39539. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39540. var _this = this;
  39541. if (!this.delayLoadingFile) {
  39542. return;
  39543. }
  39544. scene._addPendingData(this);
  39545. scene._loadFile(this.delayLoadingFile, function (data) {
  39546. if (!_this._delayLoadingFunction) {
  39547. return;
  39548. }
  39549. _this._delayLoadingFunction(JSON.parse(data), _this);
  39550. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39551. _this._delayInfo = [];
  39552. scene._removePendingData(_this);
  39553. var meshes = _this._meshes;
  39554. var numOfMeshes = meshes.length;
  39555. for (var index = 0; index < numOfMeshes; index++) {
  39556. _this._applyToMesh(meshes[index]);
  39557. }
  39558. if (onLoaded) {
  39559. onLoaded();
  39560. }
  39561. }, undefined, true);
  39562. };
  39563. /**
  39564. * Invert the geometry to move from a right handed system to a left handed one.
  39565. */
  39566. Geometry.prototype.toLeftHanded = function () {
  39567. // Flip faces
  39568. var tIndices = this.getIndices(false);
  39569. if (tIndices != null && tIndices.length > 0) {
  39570. for (var i = 0; i < tIndices.length; i += 3) {
  39571. var tTemp = tIndices[i + 0];
  39572. tIndices[i + 0] = tIndices[i + 2];
  39573. tIndices[i + 2] = tTemp;
  39574. }
  39575. this.setIndices(tIndices);
  39576. }
  39577. // Negate position.z
  39578. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39579. if (tPositions != null && tPositions.length > 0) {
  39580. for (var i = 0; i < tPositions.length; i += 3) {
  39581. tPositions[i + 2] = -tPositions[i + 2];
  39582. }
  39583. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39584. }
  39585. // Negate normal.z
  39586. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39587. if (tNormals != null && tNormals.length > 0) {
  39588. for (var i = 0; i < tNormals.length; i += 3) {
  39589. tNormals[i + 2] = -tNormals[i + 2];
  39590. }
  39591. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39592. }
  39593. };
  39594. // Cache
  39595. /** @hidden */
  39596. Geometry.prototype._resetPointsArrayCache = function () {
  39597. this._positions = null;
  39598. };
  39599. /** @hidden */
  39600. Geometry.prototype._generatePointsArray = function () {
  39601. if (this._positions)
  39602. return true;
  39603. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39604. if (!data || data.length === 0) {
  39605. return false;
  39606. }
  39607. this._positions = [];
  39608. for (var index = 0; index < data.length; index += 3) {
  39609. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39610. }
  39611. return true;
  39612. };
  39613. /**
  39614. * Gets a value indicating if the geometry is disposed
  39615. * @returns true if the geometry was disposed
  39616. */
  39617. Geometry.prototype.isDisposed = function () {
  39618. return this._isDisposed;
  39619. };
  39620. Geometry.prototype._disposeVertexArrayObjects = function () {
  39621. if (this._vertexArrayObjects) {
  39622. for (var kind in this._vertexArrayObjects) {
  39623. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39624. }
  39625. this._vertexArrayObjects = {};
  39626. }
  39627. };
  39628. /**
  39629. * Free all associated resources
  39630. */
  39631. Geometry.prototype.dispose = function () {
  39632. var meshes = this._meshes;
  39633. var numOfMeshes = meshes.length;
  39634. var index;
  39635. for (index = 0; index < numOfMeshes; index++) {
  39636. this.releaseForMesh(meshes[index]);
  39637. }
  39638. this._meshes = [];
  39639. this._disposeVertexArrayObjects();
  39640. for (var kind in this._vertexBuffers) {
  39641. this._vertexBuffers[kind].dispose();
  39642. }
  39643. this._vertexBuffers = {};
  39644. this._totalVertices = 0;
  39645. if (this._indexBuffer) {
  39646. this._engine._releaseBuffer(this._indexBuffer);
  39647. }
  39648. this._indexBuffer = null;
  39649. this._indices = [];
  39650. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39651. this.delayLoadingFile = null;
  39652. this._delayLoadingFunction = null;
  39653. this._delayInfo = [];
  39654. this._boundingInfo = null;
  39655. this._scene.removeGeometry(this);
  39656. this._isDisposed = true;
  39657. };
  39658. /**
  39659. * Clone the current geometry into a new geometry
  39660. * @param id defines the unique ID of the new geometry
  39661. * @returns a new geometry object
  39662. */
  39663. Geometry.prototype.copy = function (id) {
  39664. var vertexData = new BABYLON.VertexData();
  39665. vertexData.indices = [];
  39666. var indices = this.getIndices();
  39667. if (indices) {
  39668. for (var index = 0; index < indices.length; index++) {
  39669. vertexData.indices.push(indices[index]);
  39670. }
  39671. }
  39672. var updatable = false;
  39673. var stopChecking = false;
  39674. var kind;
  39675. for (kind in this._vertexBuffers) {
  39676. // using slice() to make a copy of the array and not just reference it
  39677. var data = this.getVerticesData(kind);
  39678. if (data instanceof Float32Array) {
  39679. vertexData.set(new Float32Array(data), kind);
  39680. }
  39681. else {
  39682. vertexData.set(data.slice(0), kind);
  39683. }
  39684. if (!stopChecking) {
  39685. var vb = this.getVertexBuffer(kind);
  39686. if (vb) {
  39687. updatable = vb.isUpdatable();
  39688. stopChecking = !updatable;
  39689. }
  39690. }
  39691. }
  39692. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39693. geometry.delayLoadState = this.delayLoadState;
  39694. geometry.delayLoadingFile = this.delayLoadingFile;
  39695. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39696. for (kind in this._delayInfo) {
  39697. geometry._delayInfo = geometry._delayInfo || [];
  39698. geometry._delayInfo.push(kind);
  39699. }
  39700. // Bounding info
  39701. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39702. return geometry;
  39703. };
  39704. /**
  39705. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39706. * @return a JSON representation of the current geometry data (without the vertices data)
  39707. */
  39708. Geometry.prototype.serialize = function () {
  39709. var serializationObject = {};
  39710. serializationObject.id = this.id;
  39711. serializationObject.updatable = this._updatable;
  39712. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39713. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39714. }
  39715. return serializationObject;
  39716. };
  39717. Geometry.prototype.toNumberArray = function (origin) {
  39718. if (Array.isArray(origin)) {
  39719. return origin;
  39720. }
  39721. else {
  39722. return Array.prototype.slice.call(origin);
  39723. }
  39724. };
  39725. /**
  39726. * Serialize all vertices data into a JSON oject
  39727. * @returns a JSON representation of the current geometry data
  39728. */
  39729. Geometry.prototype.serializeVerticeData = function () {
  39730. var serializationObject = this.serialize();
  39731. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39732. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39733. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39734. serializationObject.positions._updatable = true;
  39735. }
  39736. }
  39737. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39738. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39739. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39740. serializationObject.normals._updatable = true;
  39741. }
  39742. }
  39743. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39744. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39745. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39746. serializationObject.tangets._updatable = true;
  39747. }
  39748. }
  39749. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39750. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39751. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39752. serializationObject.uvs._updatable = true;
  39753. }
  39754. }
  39755. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39756. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39757. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39758. serializationObject.uv2s._updatable = true;
  39759. }
  39760. }
  39761. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39762. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39763. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39764. serializationObject.uv3s._updatable = true;
  39765. }
  39766. }
  39767. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39768. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39769. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39770. serializationObject.uv4s._updatable = true;
  39771. }
  39772. }
  39773. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39774. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39775. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39776. serializationObject.uv5s._updatable = true;
  39777. }
  39778. }
  39779. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39780. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39781. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39782. serializationObject.uv6s._updatable = true;
  39783. }
  39784. }
  39785. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39786. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39787. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39788. serializationObject.colors._updatable = true;
  39789. }
  39790. }
  39791. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39792. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39793. serializationObject.matricesIndices._isExpanded = true;
  39794. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39795. serializationObject.matricesIndices._updatable = true;
  39796. }
  39797. }
  39798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39799. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39800. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39801. serializationObject.matricesWeights._updatable = true;
  39802. }
  39803. }
  39804. serializationObject.indices = this.toNumberArray(this.getIndices());
  39805. return serializationObject;
  39806. };
  39807. // Statics
  39808. /**
  39809. * Extracts a clone of a mesh geometry
  39810. * @param mesh defines the source mesh
  39811. * @param id defines the unique ID of the new geometry object
  39812. * @returns the new geometry object
  39813. */
  39814. Geometry.ExtractFromMesh = function (mesh, id) {
  39815. var geometry = mesh._geometry;
  39816. if (!geometry) {
  39817. return null;
  39818. }
  39819. return geometry.copy(id);
  39820. };
  39821. /**
  39822. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39823. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39824. * Be aware Math.random() could cause collisions, but:
  39825. * "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"
  39826. * @returns a string containing a new GUID
  39827. */
  39828. Geometry.RandomId = function () {
  39829. return BABYLON.Tools.RandomId();
  39830. };
  39831. /** @hidden */
  39832. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39833. var scene = mesh.getScene();
  39834. // Geometry
  39835. var geometryId = parsedGeometry.geometryId;
  39836. if (geometryId) {
  39837. var geometry = scene.getGeometryByID(geometryId);
  39838. if (geometry) {
  39839. geometry.applyToMesh(mesh);
  39840. }
  39841. }
  39842. else if (parsedGeometry instanceof ArrayBuffer) {
  39843. var binaryInfo = mesh._binaryInfo;
  39844. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39845. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39846. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39847. }
  39848. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39849. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39850. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39851. }
  39852. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39853. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39854. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39855. }
  39856. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39857. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39858. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39859. }
  39860. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39861. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39862. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39863. }
  39864. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39865. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39866. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39867. }
  39868. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39869. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39870. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39871. }
  39872. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39873. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39874. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39875. }
  39876. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39877. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39878. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39879. }
  39880. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39881. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39882. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39883. }
  39884. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39885. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39886. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39887. }
  39888. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39889. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39890. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39891. }
  39892. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39893. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39894. mesh.setIndices(indicesData, null);
  39895. }
  39896. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39897. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39898. mesh.subMeshes = [];
  39899. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39900. var materialIndex = subMeshesData[(i * 5) + 0];
  39901. var verticesStart = subMeshesData[(i * 5) + 1];
  39902. var verticesCount = subMeshesData[(i * 5) + 2];
  39903. var indexStart = subMeshesData[(i * 5) + 3];
  39904. var indexCount = subMeshesData[(i * 5) + 4];
  39905. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39906. }
  39907. }
  39908. }
  39909. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39910. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39912. if (parsedGeometry.tangents) {
  39913. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39914. }
  39915. if (parsedGeometry.uvs) {
  39916. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39917. }
  39918. if (parsedGeometry.uvs2) {
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39920. }
  39921. if (parsedGeometry.uvs3) {
  39922. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39923. }
  39924. if (parsedGeometry.uvs4) {
  39925. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39926. }
  39927. if (parsedGeometry.uvs5) {
  39928. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39929. }
  39930. if (parsedGeometry.uvs6) {
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39932. }
  39933. if (parsedGeometry.colors) {
  39934. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39935. }
  39936. if (parsedGeometry.matricesIndices) {
  39937. if (!parsedGeometry.matricesIndices._isExpanded) {
  39938. var floatIndices = [];
  39939. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39940. var matricesIndex = parsedGeometry.matricesIndices[i];
  39941. floatIndices.push(matricesIndex & 0x000000FF);
  39942. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39943. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39944. floatIndices.push(matricesIndex >> 24);
  39945. }
  39946. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39947. }
  39948. else {
  39949. delete parsedGeometry.matricesIndices._isExpanded;
  39950. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39951. }
  39952. }
  39953. if (parsedGeometry.matricesIndicesExtra) {
  39954. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39955. var floatIndices = [];
  39956. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39957. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39958. floatIndices.push(matricesIndex & 0x000000FF);
  39959. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39960. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39961. floatIndices.push(matricesIndex >> 24);
  39962. }
  39963. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39964. }
  39965. else {
  39966. delete parsedGeometry.matricesIndices._isExpanded;
  39967. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39968. }
  39969. }
  39970. if (parsedGeometry.matricesWeights) {
  39971. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39972. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39973. }
  39974. if (parsedGeometry.matricesWeightsExtra) {
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39976. }
  39977. mesh.setIndices(parsedGeometry.indices, null);
  39978. }
  39979. // SubMeshes
  39980. if (parsedGeometry.subMeshes) {
  39981. mesh.subMeshes = [];
  39982. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39983. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39984. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39985. }
  39986. }
  39987. // Flat shading
  39988. if (mesh._shouldGenerateFlatShading) {
  39989. mesh.convertToFlatShadedMesh();
  39990. delete mesh._shouldGenerateFlatShading;
  39991. }
  39992. // Update
  39993. mesh.computeWorldMatrix(true);
  39994. // Octree
  39995. var sceneOctree = scene.selectionOctree;
  39996. if (sceneOctree !== undefined && sceneOctree !== null) {
  39997. sceneOctree.addMesh(mesh);
  39998. }
  39999. };
  40000. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40001. var epsilon = 1e-3;
  40002. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40003. return;
  40004. }
  40005. var noInfluenceBoneIndex = 0.0;
  40006. if (parsedGeometry.skeletonId > -1) {
  40007. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40008. if (!skeleton) {
  40009. return;
  40010. }
  40011. noInfluenceBoneIndex = skeleton.bones.length;
  40012. }
  40013. else {
  40014. return;
  40015. }
  40016. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40017. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40018. var matricesWeights = parsedGeometry.matricesWeights;
  40019. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40020. var influencers = parsedGeometry.numBoneInfluencer;
  40021. var size = matricesWeights.length;
  40022. for (var i = 0; i < size; i += 4) {
  40023. var weight = 0.0;
  40024. var firstZeroWeight = -1;
  40025. for (var j = 0; j < 4; j++) {
  40026. var w = matricesWeights[i + j];
  40027. weight += w;
  40028. if (w < epsilon && firstZeroWeight < 0) {
  40029. firstZeroWeight = j;
  40030. }
  40031. }
  40032. if (matricesWeightsExtra) {
  40033. for (var j = 0; j < 4; j++) {
  40034. var w = matricesWeightsExtra[i + j];
  40035. weight += w;
  40036. if (w < epsilon && firstZeroWeight < 0) {
  40037. firstZeroWeight = j + 4;
  40038. }
  40039. }
  40040. }
  40041. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40042. firstZeroWeight = influencers - 1;
  40043. }
  40044. if (weight > epsilon) {
  40045. var mweight = 1.0 / weight;
  40046. for (var j = 0; j < 4; j++) {
  40047. matricesWeights[i + j] *= mweight;
  40048. }
  40049. if (matricesWeightsExtra) {
  40050. for (var j = 0; j < 4; j++) {
  40051. matricesWeightsExtra[i + j] *= mweight;
  40052. }
  40053. }
  40054. }
  40055. else {
  40056. if (firstZeroWeight >= 4) {
  40057. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40058. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40059. }
  40060. else {
  40061. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40062. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40063. }
  40064. }
  40065. }
  40066. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40067. if (parsedGeometry.matricesWeightsExtra) {
  40068. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40069. }
  40070. };
  40071. /**
  40072. * Create a new geometry from persisted data (Using .babylon file format)
  40073. * @param parsedVertexData defines the persisted data
  40074. * @param scene defines the hosting scene
  40075. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40076. * @returns the new geometry object
  40077. */
  40078. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40079. if (scene.getGeometryByID(parsedVertexData.id)) {
  40080. return null; // null since geometry could be something else than a box...
  40081. }
  40082. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40083. if (BABYLON.Tags) {
  40084. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40085. }
  40086. if (parsedVertexData.delayLoadingFile) {
  40087. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40088. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40089. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40090. geometry._delayInfo = [];
  40091. if (parsedVertexData.hasUVs) {
  40092. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40093. }
  40094. if (parsedVertexData.hasUVs2) {
  40095. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40096. }
  40097. if (parsedVertexData.hasUVs3) {
  40098. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40099. }
  40100. if (parsedVertexData.hasUVs4) {
  40101. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40102. }
  40103. if (parsedVertexData.hasUVs5) {
  40104. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40105. }
  40106. if (parsedVertexData.hasUVs6) {
  40107. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40108. }
  40109. if (parsedVertexData.hasColors) {
  40110. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40111. }
  40112. if (parsedVertexData.hasMatricesIndices) {
  40113. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40114. }
  40115. if (parsedVertexData.hasMatricesWeights) {
  40116. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40117. }
  40118. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40119. }
  40120. else {
  40121. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40122. }
  40123. scene.pushGeometry(geometry, true);
  40124. return geometry;
  40125. };
  40126. return Geometry;
  40127. }());
  40128. BABYLON.Geometry = Geometry;
  40129. // Primitives
  40130. /// Abstract class
  40131. /**
  40132. * Abstract class used to provide common services for all typed geometries
  40133. * @hidden
  40134. */
  40135. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40136. __extends(_PrimitiveGeometry, _super);
  40137. /**
  40138. * Creates a new typed geometry
  40139. * @param id defines the unique ID of the geometry
  40140. * @param scene defines the hosting scene
  40141. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40142. * @param mesh defines the hosting mesh (can be null)
  40143. */
  40144. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40145. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40146. if (mesh === void 0) { mesh = null; }
  40147. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40148. _this._canBeRegenerated = _canBeRegenerated;
  40149. _this._beingRegenerated = true;
  40150. _this.regenerate();
  40151. _this._beingRegenerated = false;
  40152. return _this;
  40153. }
  40154. /**
  40155. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40156. * @returns true if the geometry can be regenerated
  40157. */
  40158. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40159. return this._canBeRegenerated;
  40160. };
  40161. /**
  40162. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40163. */
  40164. _PrimitiveGeometry.prototype.regenerate = function () {
  40165. if (!this._canBeRegenerated) {
  40166. return;
  40167. }
  40168. this._beingRegenerated = true;
  40169. this.setAllVerticesData(this._regenerateVertexData(), false);
  40170. this._beingRegenerated = false;
  40171. };
  40172. /**
  40173. * Clone the geometry
  40174. * @param id defines the unique ID of the new geometry
  40175. * @returns the new geometry
  40176. */
  40177. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40178. return _super.prototype.copy.call(this, id);
  40179. };
  40180. // overrides
  40181. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40182. if (!this._beingRegenerated) {
  40183. return;
  40184. }
  40185. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40186. };
  40187. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40188. if (!this._beingRegenerated) {
  40189. return;
  40190. }
  40191. _super.prototype.setVerticesData.call(this, kind, data, false);
  40192. };
  40193. // to override
  40194. /** @hidden */
  40195. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40196. throw new Error("Abstract method");
  40197. };
  40198. _PrimitiveGeometry.prototype.copy = function (id) {
  40199. throw new Error("Must be overriden in sub-classes.");
  40200. };
  40201. _PrimitiveGeometry.prototype.serialize = function () {
  40202. var serializationObject = _super.prototype.serialize.call(this);
  40203. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40204. return serializationObject;
  40205. };
  40206. return _PrimitiveGeometry;
  40207. }(Geometry));
  40208. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40209. /**
  40210. * Creates a ribbon geometry
  40211. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40212. */
  40213. var RibbonGeometry = /** @class */ (function (_super) {
  40214. __extends(RibbonGeometry, _super);
  40215. /**
  40216. * Creates a ribbon geometry
  40217. * @param id defines the unique ID of the geometry
  40218. * @param scene defines the hosting scene
  40219. * @param pathArray defines the array of paths to use
  40220. * @param closeArray defines if the last path and the first path must be joined
  40221. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40222. * @param offset defines the offset between points
  40223. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40224. * @param mesh defines the hosting mesh (can be null)
  40225. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40226. */
  40227. function RibbonGeometry(id, scene,
  40228. /**
  40229. * Defines the array of paths to use
  40230. */
  40231. pathArray,
  40232. /**
  40233. * Defines if the last and first points of each path in your pathArray must be joined
  40234. */
  40235. closeArray,
  40236. /**
  40237. * Defines if the last and first points of each path in your pathArray must be joined
  40238. */
  40239. closePath,
  40240. /**
  40241. * Defines the offset between points
  40242. */
  40243. offset, canBeRegenerated, mesh,
  40244. /**
  40245. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40246. */
  40247. side) {
  40248. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40249. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40250. _this.pathArray = pathArray;
  40251. _this.closeArray = closeArray;
  40252. _this.closePath = closePath;
  40253. _this.offset = offset;
  40254. _this.side = side;
  40255. return _this;
  40256. }
  40257. /** @hidden */
  40258. RibbonGeometry.prototype._regenerateVertexData = function () {
  40259. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40260. };
  40261. RibbonGeometry.prototype.copy = function (id) {
  40262. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40263. };
  40264. return RibbonGeometry;
  40265. }(_PrimitiveGeometry));
  40266. BABYLON.RibbonGeometry = RibbonGeometry;
  40267. /**
  40268. * Creates a box geometry
  40269. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40270. */
  40271. var BoxGeometry = /** @class */ (function (_super) {
  40272. __extends(BoxGeometry, _super);
  40273. /**
  40274. * Creates a box geometry
  40275. * @param id defines the unique ID of the geometry
  40276. * @param scene defines the hosting scene
  40277. * @param size defines the zise of the box (width, height and depth are the same)
  40278. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40279. * @param mesh defines the hosting mesh (can be null)
  40280. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40281. */
  40282. function BoxGeometry(id, scene,
  40283. /**
  40284. * Defines the zise of the box (width, height and depth are the same)
  40285. */
  40286. size, canBeRegenerated, mesh,
  40287. /**
  40288. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40289. */
  40290. side) {
  40291. if (mesh === void 0) { mesh = null; }
  40292. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40293. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40294. _this.size = size;
  40295. _this.side = side;
  40296. return _this;
  40297. }
  40298. BoxGeometry.prototype._regenerateVertexData = function () {
  40299. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40300. };
  40301. BoxGeometry.prototype.copy = function (id) {
  40302. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40303. };
  40304. BoxGeometry.prototype.serialize = function () {
  40305. var serializationObject = _super.prototype.serialize.call(this);
  40306. serializationObject.size = this.size;
  40307. return serializationObject;
  40308. };
  40309. BoxGeometry.Parse = function (parsedBox, scene) {
  40310. if (scene.getGeometryByID(parsedBox.id)) {
  40311. return null; // null since geometry could be something else than a box...
  40312. }
  40313. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40314. if (BABYLON.Tags) {
  40315. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40316. }
  40317. scene.pushGeometry(box, true);
  40318. return box;
  40319. };
  40320. return BoxGeometry;
  40321. }(_PrimitiveGeometry));
  40322. BABYLON.BoxGeometry = BoxGeometry;
  40323. /**
  40324. * Creates a sphere geometry
  40325. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40326. */
  40327. var SphereGeometry = /** @class */ (function (_super) {
  40328. __extends(SphereGeometry, _super);
  40329. /**
  40330. * Create a new sphere geometry
  40331. * @param id defines the unique ID of the geometry
  40332. * @param scene defines the hosting scene
  40333. * @param segments defines the number of segments to use to create the sphere
  40334. * @param diameter defines the diameter of the sphere
  40335. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40336. * @param mesh defines the hosting mesh (can be null)
  40337. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40338. */
  40339. function SphereGeometry(id, scene,
  40340. /**
  40341. * Defines the number of segments to use to create the sphere
  40342. */
  40343. segments,
  40344. /**
  40345. * Defines the diameter of the sphere
  40346. */
  40347. diameter, canBeRegenerated, mesh,
  40348. /**
  40349. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40350. */
  40351. side) {
  40352. if (mesh === void 0) { mesh = null; }
  40353. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40354. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40355. _this.segments = segments;
  40356. _this.diameter = diameter;
  40357. _this.side = side;
  40358. return _this;
  40359. }
  40360. SphereGeometry.prototype._regenerateVertexData = function () {
  40361. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40362. };
  40363. SphereGeometry.prototype.copy = function (id) {
  40364. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40365. };
  40366. SphereGeometry.prototype.serialize = function () {
  40367. var serializationObject = _super.prototype.serialize.call(this);
  40368. serializationObject.segments = this.segments;
  40369. serializationObject.diameter = this.diameter;
  40370. return serializationObject;
  40371. };
  40372. SphereGeometry.Parse = function (parsedSphere, scene) {
  40373. if (scene.getGeometryByID(parsedSphere.id)) {
  40374. return null; // null since geometry could be something else than a sphere...
  40375. }
  40376. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40377. if (BABYLON.Tags) {
  40378. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40379. }
  40380. scene.pushGeometry(sphere, true);
  40381. return sphere;
  40382. };
  40383. return SphereGeometry;
  40384. }(_PrimitiveGeometry));
  40385. BABYLON.SphereGeometry = SphereGeometry;
  40386. /**
  40387. * Creates a disc geometry
  40388. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40389. */
  40390. var DiscGeometry = /** @class */ (function (_super) {
  40391. __extends(DiscGeometry, _super);
  40392. /**
  40393. * Creates a new disc geometry
  40394. * @param id defines the unique ID of the geometry
  40395. * @param scene defines the hosting scene
  40396. * @param radius defines the radius of the disc
  40397. * @param tessellation defines the tesselation factor to apply to the disc
  40398. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40399. * @param mesh defines the hosting mesh (can be null)
  40400. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40401. */
  40402. function DiscGeometry(id, scene,
  40403. /**
  40404. * Defines the radius of the disc
  40405. */
  40406. radius,
  40407. /**
  40408. * Defines the tesselation factor to apply to the disc
  40409. */
  40410. tessellation, canBeRegenerated, mesh,
  40411. /**
  40412. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40413. */
  40414. side) {
  40415. if (mesh === void 0) { mesh = null; }
  40416. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40417. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40418. _this.radius = radius;
  40419. _this.tessellation = tessellation;
  40420. _this.side = side;
  40421. return _this;
  40422. }
  40423. DiscGeometry.prototype._regenerateVertexData = function () {
  40424. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40425. };
  40426. DiscGeometry.prototype.copy = function (id) {
  40427. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40428. };
  40429. return DiscGeometry;
  40430. }(_PrimitiveGeometry));
  40431. BABYLON.DiscGeometry = DiscGeometry;
  40432. /**
  40433. * Creates a new cylinder geometry
  40434. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40435. */
  40436. var CylinderGeometry = /** @class */ (function (_super) {
  40437. __extends(CylinderGeometry, _super);
  40438. /**
  40439. * Creates a new cylinder geometry
  40440. * @param id defines the unique ID of the geometry
  40441. * @param scene defines the hosting scene
  40442. * @param height defines the height of the cylinder
  40443. * @param diameterTop defines the diameter of the cylinder's top cap
  40444. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40445. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40446. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40447. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40448. * @param mesh defines the hosting mesh (can be null)
  40449. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40450. */
  40451. function CylinderGeometry(id, scene,
  40452. /**
  40453. * Defines the height of the cylinder
  40454. */
  40455. height,
  40456. /**
  40457. * Defines the diameter of the cylinder's top cap
  40458. */
  40459. diameterTop,
  40460. /**
  40461. * Defines the diameter of the cylinder's bottom cap
  40462. */
  40463. diameterBottom,
  40464. /**
  40465. * Defines the tessellation factor to apply to the cylinder
  40466. */
  40467. tessellation,
  40468. /**
  40469. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40470. */
  40471. subdivisions, canBeRegenerated, mesh,
  40472. /**
  40473. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40474. */
  40475. side) {
  40476. if (subdivisions === void 0) { subdivisions = 1; }
  40477. if (mesh === void 0) { mesh = null; }
  40478. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40479. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40480. _this.height = height;
  40481. _this.diameterTop = diameterTop;
  40482. _this.diameterBottom = diameterBottom;
  40483. _this.tessellation = tessellation;
  40484. _this.subdivisions = subdivisions;
  40485. _this.side = side;
  40486. return _this;
  40487. }
  40488. CylinderGeometry.prototype._regenerateVertexData = function () {
  40489. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40490. };
  40491. CylinderGeometry.prototype.copy = function (id) {
  40492. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40493. };
  40494. CylinderGeometry.prototype.serialize = function () {
  40495. var serializationObject = _super.prototype.serialize.call(this);
  40496. serializationObject.height = this.height;
  40497. serializationObject.diameterTop = this.diameterTop;
  40498. serializationObject.diameterBottom = this.diameterBottom;
  40499. serializationObject.tessellation = this.tessellation;
  40500. return serializationObject;
  40501. };
  40502. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40503. if (scene.getGeometryByID(parsedCylinder.id)) {
  40504. return null; // null since geometry could be something else than a cylinder...
  40505. }
  40506. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40507. if (BABYLON.Tags) {
  40508. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40509. }
  40510. scene.pushGeometry(cylinder, true);
  40511. return cylinder;
  40512. };
  40513. return CylinderGeometry;
  40514. }(_PrimitiveGeometry));
  40515. BABYLON.CylinderGeometry = CylinderGeometry;
  40516. /**
  40517. * Creates a new torus geometry
  40518. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40519. */
  40520. var TorusGeometry = /** @class */ (function (_super) {
  40521. __extends(TorusGeometry, _super);
  40522. /**
  40523. * Creates a new torus geometry
  40524. * @param id defines the unique ID of the geometry
  40525. * @param scene defines the hosting scene
  40526. * @param diameter defines the diameter of the torus
  40527. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40528. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40529. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40530. * @param mesh defines the hosting mesh (can be null)
  40531. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40532. */
  40533. function TorusGeometry(id, scene,
  40534. /**
  40535. * Defines the diameter of the torus
  40536. */
  40537. diameter,
  40538. /**
  40539. * Defines the thickness of the torus (ie. internal diameter)
  40540. */
  40541. thickness,
  40542. /**
  40543. * Defines the tesselation factor to apply to the torus
  40544. */
  40545. tessellation, canBeRegenerated, mesh,
  40546. /**
  40547. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40548. */
  40549. side) {
  40550. if (mesh === void 0) { mesh = null; }
  40551. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40552. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40553. _this.diameter = diameter;
  40554. _this.thickness = thickness;
  40555. _this.tessellation = tessellation;
  40556. _this.side = side;
  40557. return _this;
  40558. }
  40559. TorusGeometry.prototype._regenerateVertexData = function () {
  40560. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40561. };
  40562. TorusGeometry.prototype.copy = function (id) {
  40563. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40564. };
  40565. TorusGeometry.prototype.serialize = function () {
  40566. var serializationObject = _super.prototype.serialize.call(this);
  40567. serializationObject.diameter = this.diameter;
  40568. serializationObject.thickness = this.thickness;
  40569. serializationObject.tessellation = this.tessellation;
  40570. return serializationObject;
  40571. };
  40572. TorusGeometry.Parse = function (parsedTorus, scene) {
  40573. if (scene.getGeometryByID(parsedTorus.id)) {
  40574. return null; // null since geometry could be something else than a torus...
  40575. }
  40576. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40577. if (BABYLON.Tags) {
  40578. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40579. }
  40580. scene.pushGeometry(torus, true);
  40581. return torus;
  40582. };
  40583. return TorusGeometry;
  40584. }(_PrimitiveGeometry));
  40585. BABYLON.TorusGeometry = TorusGeometry;
  40586. /**
  40587. * Creates a new ground geometry
  40588. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40589. */
  40590. var GroundGeometry = /** @class */ (function (_super) {
  40591. __extends(GroundGeometry, _super);
  40592. /**
  40593. * Creates a new ground geometry
  40594. * @param id defines the unique ID of the geometry
  40595. * @param scene defines the hosting scene
  40596. * @param width defines the width of the ground
  40597. * @param height defines the height of the ground
  40598. * @param subdivisions defines the subdivisions to apply to the ground
  40599. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40600. * @param mesh defines the hosting mesh (can be null)
  40601. */
  40602. function GroundGeometry(id, scene,
  40603. /**
  40604. * Defines the width of the ground
  40605. */
  40606. width,
  40607. /**
  40608. * Defines the height of the ground
  40609. */
  40610. height,
  40611. /**
  40612. * Defines the subdivisions to apply to the ground
  40613. */
  40614. subdivisions, canBeRegenerated, mesh) {
  40615. if (mesh === void 0) { mesh = null; }
  40616. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40617. _this.width = width;
  40618. _this.height = height;
  40619. _this.subdivisions = subdivisions;
  40620. return _this;
  40621. }
  40622. GroundGeometry.prototype._regenerateVertexData = function () {
  40623. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40624. };
  40625. GroundGeometry.prototype.copy = function (id) {
  40626. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40627. };
  40628. GroundGeometry.prototype.serialize = function () {
  40629. var serializationObject = _super.prototype.serialize.call(this);
  40630. serializationObject.width = this.width;
  40631. serializationObject.height = this.height;
  40632. serializationObject.subdivisions = this.subdivisions;
  40633. return serializationObject;
  40634. };
  40635. GroundGeometry.Parse = function (parsedGround, scene) {
  40636. if (scene.getGeometryByID(parsedGround.id)) {
  40637. return null; // null since geometry could be something else than a ground...
  40638. }
  40639. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40640. if (BABYLON.Tags) {
  40641. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40642. }
  40643. scene.pushGeometry(ground, true);
  40644. return ground;
  40645. };
  40646. return GroundGeometry;
  40647. }(_PrimitiveGeometry));
  40648. BABYLON.GroundGeometry = GroundGeometry;
  40649. /**
  40650. * Creates a tiled ground geometry
  40651. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40652. */
  40653. var TiledGroundGeometry = /** @class */ (function (_super) {
  40654. __extends(TiledGroundGeometry, _super);
  40655. /**
  40656. * Creates a tiled ground geometry
  40657. * @param id defines the unique ID of the geometry
  40658. * @param scene defines the hosting scene
  40659. * @param xmin defines the minimum value on X axis
  40660. * @param zmin defines the minimum value on Z axis
  40661. * @param xmax defines the maximum value on X axis
  40662. * @param zmax defines the maximum value on Z axis
  40663. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40664. * @param precision defines the precision to use when computing the tiles
  40665. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40666. * @param mesh defines the hosting mesh (can be null)
  40667. */
  40668. function TiledGroundGeometry(id, scene,
  40669. /**
  40670. * Defines the minimum value on X axis
  40671. */
  40672. xmin,
  40673. /**
  40674. * Defines the minimum value on Z axis
  40675. */
  40676. zmin,
  40677. /**
  40678. * Defines the maximum value on X axis
  40679. */
  40680. xmax,
  40681. /**
  40682. * Defines the maximum value on Z axis
  40683. */
  40684. zmax,
  40685. /**
  40686. * Defines the subdivisions to apply to the ground
  40687. */
  40688. subdivisions,
  40689. /**
  40690. * Defines the precision to use when computing the tiles
  40691. */
  40692. precision, canBeRegenerated, mesh) {
  40693. if (mesh === void 0) { mesh = null; }
  40694. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40695. _this.xmin = xmin;
  40696. _this.zmin = zmin;
  40697. _this.xmax = xmax;
  40698. _this.zmax = zmax;
  40699. _this.subdivisions = subdivisions;
  40700. _this.precision = precision;
  40701. return _this;
  40702. }
  40703. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40704. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40705. };
  40706. TiledGroundGeometry.prototype.copy = function (id) {
  40707. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40708. };
  40709. return TiledGroundGeometry;
  40710. }(_PrimitiveGeometry));
  40711. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40712. /**
  40713. * Creates a plane geometry
  40714. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40715. */
  40716. var PlaneGeometry = /** @class */ (function (_super) {
  40717. __extends(PlaneGeometry, _super);
  40718. /**
  40719. * Creates a plane geometry
  40720. * @param id defines the unique ID of the geometry
  40721. * @param scene defines the hosting scene
  40722. * @param size defines the size of the plane (width === height)
  40723. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40724. * @param mesh defines the hosting mesh (can be null)
  40725. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40726. */
  40727. function PlaneGeometry(id, scene,
  40728. /**
  40729. * Defines the size of the plane (width === height)
  40730. */
  40731. size, canBeRegenerated, mesh,
  40732. /**
  40733. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40734. */
  40735. side) {
  40736. if (mesh === void 0) { mesh = null; }
  40737. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40738. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40739. _this.size = size;
  40740. _this.side = side;
  40741. return _this;
  40742. }
  40743. PlaneGeometry.prototype._regenerateVertexData = function () {
  40744. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40745. };
  40746. PlaneGeometry.prototype.copy = function (id) {
  40747. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40748. };
  40749. PlaneGeometry.prototype.serialize = function () {
  40750. var serializationObject = _super.prototype.serialize.call(this);
  40751. serializationObject.size = this.size;
  40752. return serializationObject;
  40753. };
  40754. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40755. if (scene.getGeometryByID(parsedPlane.id)) {
  40756. return null; // null since geometry could be something else than a ground...
  40757. }
  40758. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40759. if (BABYLON.Tags) {
  40760. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40761. }
  40762. scene.pushGeometry(plane, true);
  40763. return plane;
  40764. };
  40765. return PlaneGeometry;
  40766. }(_PrimitiveGeometry));
  40767. BABYLON.PlaneGeometry = PlaneGeometry;
  40768. /**
  40769. * Creates a torus knot geometry
  40770. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40771. */
  40772. var TorusKnotGeometry = /** @class */ (function (_super) {
  40773. __extends(TorusKnotGeometry, _super);
  40774. /**
  40775. * Creates a torus knot geometry
  40776. * @param id defines the unique ID of the geometry
  40777. * @param scene defines the hosting scene
  40778. * @param radius defines the radius of the torus knot
  40779. * @param tube defines the thickness of the torus knot tube
  40780. * @param radialSegments defines the number of radial segments
  40781. * @param tubularSegments defines the number of tubular segments
  40782. * @param p defines the first number of windings
  40783. * @param q defines the second number of windings
  40784. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40785. * @param mesh defines the hosting mesh (can be null)
  40786. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40787. */
  40788. function TorusKnotGeometry(id, scene,
  40789. /**
  40790. * Defines the radius of the torus knot
  40791. */
  40792. radius,
  40793. /**
  40794. * Defines the thickness of the torus knot tube
  40795. */
  40796. tube,
  40797. /**
  40798. * Defines the number of radial segments
  40799. */
  40800. radialSegments,
  40801. /**
  40802. * Defines the number of tubular segments
  40803. */
  40804. tubularSegments,
  40805. /**
  40806. * Defines the first number of windings
  40807. */
  40808. p,
  40809. /**
  40810. * Defines the second number of windings
  40811. */
  40812. q, canBeRegenerated, mesh,
  40813. /**
  40814. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40815. */
  40816. side) {
  40817. if (mesh === void 0) { mesh = null; }
  40818. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40819. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40820. _this.radius = radius;
  40821. _this.tube = tube;
  40822. _this.radialSegments = radialSegments;
  40823. _this.tubularSegments = tubularSegments;
  40824. _this.p = p;
  40825. _this.q = q;
  40826. _this.side = side;
  40827. return _this;
  40828. }
  40829. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40830. 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 });
  40831. };
  40832. TorusKnotGeometry.prototype.copy = function (id) {
  40833. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40834. };
  40835. TorusKnotGeometry.prototype.serialize = function () {
  40836. var serializationObject = _super.prototype.serialize.call(this);
  40837. serializationObject.radius = this.radius;
  40838. serializationObject.tube = this.tube;
  40839. serializationObject.radialSegments = this.radialSegments;
  40840. serializationObject.tubularSegments = this.tubularSegments;
  40841. serializationObject.p = this.p;
  40842. serializationObject.q = this.q;
  40843. return serializationObject;
  40844. };
  40845. ;
  40846. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40847. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40848. return null; // null since geometry could be something else than a ground...
  40849. }
  40850. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40851. if (BABYLON.Tags) {
  40852. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40853. }
  40854. scene.pushGeometry(torusKnot, true);
  40855. return torusKnot;
  40856. };
  40857. return TorusKnotGeometry;
  40858. }(_PrimitiveGeometry));
  40859. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40860. //}
  40861. })(BABYLON || (BABYLON = {}));
  40862. //# sourceMappingURL=babylon.geometry.js.map
  40863. var BABYLON;
  40864. (function (BABYLON) {
  40865. /**
  40866. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40867. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40868. */
  40869. var PostProcessManager = /** @class */ (function () {
  40870. /**
  40871. * Creates a new instance PostProcess
  40872. * @param scene The scene that the post process is associated with.
  40873. */
  40874. function PostProcessManager(scene) {
  40875. this._vertexBuffers = {};
  40876. this._scene = scene;
  40877. }
  40878. PostProcessManager.prototype._prepareBuffers = function () {
  40879. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40880. return;
  40881. }
  40882. // VBO
  40883. var vertices = [];
  40884. vertices.push(1, 1);
  40885. vertices.push(-1, 1);
  40886. vertices.push(-1, -1);
  40887. vertices.push(1, -1);
  40888. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40889. this._buildIndexBuffer();
  40890. };
  40891. PostProcessManager.prototype._buildIndexBuffer = function () {
  40892. // Indices
  40893. var indices = [];
  40894. indices.push(0);
  40895. indices.push(1);
  40896. indices.push(2);
  40897. indices.push(0);
  40898. indices.push(2);
  40899. indices.push(3);
  40900. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40901. };
  40902. /**
  40903. * Rebuilds the vertex buffers of the manager.
  40904. */
  40905. PostProcessManager.prototype._rebuild = function () {
  40906. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40907. if (!vb) {
  40908. return;
  40909. }
  40910. vb._rebuild();
  40911. this._buildIndexBuffer();
  40912. };
  40913. // Methods
  40914. /**
  40915. * Prepares a frame to be run through a post process.
  40916. * @param sourceTexture The input texture to the post procesess. (default: null)
  40917. * @param postProcesses An array of post processes to be run. (default: null)
  40918. * @returns True if the post processes were able to be run.
  40919. */
  40920. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40921. if (sourceTexture === void 0) { sourceTexture = null; }
  40922. if (postProcesses === void 0) { postProcesses = null; }
  40923. var camera = this._scene.activeCamera;
  40924. if (!camera) {
  40925. return false;
  40926. }
  40927. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40928. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40929. return false;
  40930. }
  40931. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40932. return true;
  40933. };
  40934. /**
  40935. * Manually render a set of post processes to a texture.
  40936. * @param postProcesses An array of post processes to be run.
  40937. * @param targetTexture The target texture to render to.
  40938. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40939. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  40940. * @param lodLevel defines which lod of the texture to render to
  40941. */
  40942. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  40943. if (targetTexture === void 0) { targetTexture = null; }
  40944. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40945. if (faceIndex === void 0) { faceIndex = 0; }
  40946. if (lodLevel === void 0) { lodLevel = 0; }
  40947. var engine = this._scene.getEngine();
  40948. for (var index = 0; index < postProcesses.length; index++) {
  40949. if (index < postProcesses.length - 1) {
  40950. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40951. }
  40952. else {
  40953. if (targetTexture) {
  40954. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  40955. }
  40956. else {
  40957. engine.restoreDefaultFramebuffer();
  40958. }
  40959. }
  40960. var pp = postProcesses[index];
  40961. var effect = pp.apply();
  40962. if (effect) {
  40963. pp.onBeforeRenderObservable.notifyObservers(effect);
  40964. // VBOs
  40965. this._prepareBuffers();
  40966. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40967. // Draw order
  40968. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40969. pp.onAfterRenderObservable.notifyObservers(effect);
  40970. }
  40971. }
  40972. // Restore depth buffer
  40973. engine.setDepthBuffer(true);
  40974. engine.setDepthWrite(true);
  40975. };
  40976. /**
  40977. * Finalize the result of the output of the postprocesses.
  40978. * @param doNotPresent If true the result will not be displayed to the screen.
  40979. * @param targetTexture The target texture to render to.
  40980. * @param faceIndex The index of the face to bind the target texture to.
  40981. * @param postProcesses The array of post processes to render.
  40982. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40983. */
  40984. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40985. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40986. var camera = this._scene.activeCamera;
  40987. if (!camera) {
  40988. return;
  40989. }
  40990. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40991. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40992. return;
  40993. }
  40994. var engine = this._scene.getEngine();
  40995. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40996. var pp = postProcesses[index];
  40997. if (index < len - 1) {
  40998. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40999. }
  41000. else {
  41001. if (targetTexture) {
  41002. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  41003. pp._outputTexture = targetTexture;
  41004. }
  41005. else {
  41006. engine.restoreDefaultFramebuffer();
  41007. pp._outputTexture = null;
  41008. }
  41009. }
  41010. if (doNotPresent) {
  41011. break;
  41012. }
  41013. var effect = pp.apply();
  41014. if (effect) {
  41015. pp.onBeforeRenderObservable.notifyObservers(effect);
  41016. // VBOs
  41017. this._prepareBuffers();
  41018. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41019. // Draw order
  41020. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  41021. pp.onAfterRenderObservable.notifyObservers(effect);
  41022. }
  41023. }
  41024. // Restore states
  41025. engine.setDepthBuffer(true);
  41026. engine.setDepthWrite(true);
  41027. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41028. };
  41029. /**
  41030. * Disposes of the post process manager.
  41031. */
  41032. PostProcessManager.prototype.dispose = function () {
  41033. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41034. if (buffer) {
  41035. buffer.dispose();
  41036. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  41037. }
  41038. if (this._indexBuffer) {
  41039. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41040. this._indexBuffer = null;
  41041. }
  41042. };
  41043. return PostProcessManager;
  41044. }());
  41045. BABYLON.PostProcessManager = PostProcessManager;
  41046. })(BABYLON || (BABYLON = {}));
  41047. //# sourceMappingURL=babylon.postProcessManager.js.map
  41048. var BABYLON;
  41049. (function (BABYLON) {
  41050. /**
  41051. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41052. */
  41053. var PerformanceMonitor = /** @class */ (function () {
  41054. /**
  41055. * constructor
  41056. * @param frameSampleSize The number of samples required to saturate the sliding window
  41057. */
  41058. function PerformanceMonitor(frameSampleSize) {
  41059. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41060. this._enabled = true;
  41061. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41062. }
  41063. /**
  41064. * Samples current frame
  41065. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41066. */
  41067. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41068. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41069. if (!this._enabled)
  41070. return;
  41071. if (this._lastFrameTimeMs != null) {
  41072. var dt = timeMs - this._lastFrameTimeMs;
  41073. this._rollingFrameTime.add(dt);
  41074. }
  41075. this._lastFrameTimeMs = timeMs;
  41076. };
  41077. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41078. /**
  41079. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41080. * @return Average frame time in milliseconds
  41081. */
  41082. get: function () {
  41083. return this._rollingFrameTime.average;
  41084. },
  41085. enumerable: true,
  41086. configurable: true
  41087. });
  41088. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41089. /**
  41090. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41091. * @return Frame time variance in milliseconds squared
  41092. */
  41093. get: function () {
  41094. return this._rollingFrameTime.variance;
  41095. },
  41096. enumerable: true,
  41097. configurable: true
  41098. });
  41099. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41100. /**
  41101. * Returns the frame time of the most recent frame
  41102. * @return Frame time in milliseconds
  41103. */
  41104. get: function () {
  41105. return this._rollingFrameTime.history(0);
  41106. },
  41107. enumerable: true,
  41108. configurable: true
  41109. });
  41110. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41111. /**
  41112. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41113. * @return Framerate in frames per second
  41114. */
  41115. get: function () {
  41116. return 1000.0 / this._rollingFrameTime.average;
  41117. },
  41118. enumerable: true,
  41119. configurable: true
  41120. });
  41121. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41122. /**
  41123. * Returns the average framerate in frames per second using the most recent frame time
  41124. * @return Framerate in frames per second
  41125. */
  41126. get: function () {
  41127. var history = this._rollingFrameTime.history(0);
  41128. if (history === 0) {
  41129. return 0;
  41130. }
  41131. return 1000.0 / history;
  41132. },
  41133. enumerable: true,
  41134. configurable: true
  41135. });
  41136. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41137. /**
  41138. * Returns true if enough samples have been taken to completely fill the sliding window
  41139. * @return true if saturated
  41140. */
  41141. get: function () {
  41142. return this._rollingFrameTime.isSaturated();
  41143. },
  41144. enumerable: true,
  41145. configurable: true
  41146. });
  41147. /**
  41148. * Enables contributions to the sliding window sample set
  41149. */
  41150. PerformanceMonitor.prototype.enable = function () {
  41151. this._enabled = true;
  41152. };
  41153. /**
  41154. * Disables contributions to the sliding window sample set
  41155. * Samples will not be interpolated over the disabled period
  41156. */
  41157. PerformanceMonitor.prototype.disable = function () {
  41158. this._enabled = false;
  41159. //clear last sample to avoid interpolating over the disabled period when next enabled
  41160. this._lastFrameTimeMs = null;
  41161. };
  41162. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41163. /**
  41164. * Returns true if sampling is enabled
  41165. * @return true if enabled
  41166. */
  41167. get: function () {
  41168. return this._enabled;
  41169. },
  41170. enumerable: true,
  41171. configurable: true
  41172. });
  41173. /**
  41174. * Resets performance monitor
  41175. */
  41176. PerformanceMonitor.prototype.reset = function () {
  41177. //clear last sample to avoid interpolating over the disabled period when next enabled
  41178. this._lastFrameTimeMs = null;
  41179. //wipe record
  41180. this._rollingFrameTime.reset();
  41181. };
  41182. return PerformanceMonitor;
  41183. }());
  41184. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41185. /**
  41186. * RollingAverage
  41187. *
  41188. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41189. */
  41190. var RollingAverage = /** @class */ (function () {
  41191. /**
  41192. * constructor
  41193. * @param length The number of samples required to saturate the sliding window
  41194. */
  41195. function RollingAverage(length) {
  41196. this._samples = new Array(length);
  41197. this.reset();
  41198. }
  41199. /**
  41200. * Adds a sample to the sample set
  41201. * @param v The sample value
  41202. */
  41203. RollingAverage.prototype.add = function (v) {
  41204. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41205. var delta;
  41206. //we need to check if we've already wrapped round
  41207. if (this.isSaturated()) {
  41208. //remove bottom of stack from mean
  41209. var bottomValue = this._samples[this._pos];
  41210. delta = bottomValue - this.average;
  41211. this.average -= delta / (this._sampleCount - 1);
  41212. this._m2 -= delta * (bottomValue - this.average);
  41213. }
  41214. else {
  41215. this._sampleCount++;
  41216. }
  41217. //add new value to mean
  41218. delta = v - this.average;
  41219. this.average += delta / (this._sampleCount);
  41220. this._m2 += delta * (v - this.average);
  41221. //set the new variance
  41222. this.variance = this._m2 / (this._sampleCount - 1);
  41223. this._samples[this._pos] = v;
  41224. this._pos++;
  41225. this._pos %= this._samples.length; //positive wrap around
  41226. };
  41227. /**
  41228. * Returns previously added values or null if outside of history or outside the sliding window domain
  41229. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41230. * @return Value previously recorded with add() or null if outside of range
  41231. */
  41232. RollingAverage.prototype.history = function (i) {
  41233. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41234. return 0;
  41235. }
  41236. var i0 = this._wrapPosition(this._pos - 1.0);
  41237. return this._samples[this._wrapPosition(i0 - i)];
  41238. };
  41239. /**
  41240. * Returns true if enough samples have been taken to completely fill the sliding window
  41241. * @return true if sample-set saturated
  41242. */
  41243. RollingAverage.prototype.isSaturated = function () {
  41244. return this._sampleCount >= this._samples.length;
  41245. };
  41246. /**
  41247. * Resets the rolling average (equivalent to 0 samples taken so far)
  41248. */
  41249. RollingAverage.prototype.reset = function () {
  41250. this.average = 0;
  41251. this.variance = 0;
  41252. this._sampleCount = 0;
  41253. this._pos = 0;
  41254. this._m2 = 0;
  41255. };
  41256. /**
  41257. * Wraps a value around the sample range boundaries
  41258. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41259. * @return Wrapped position in sample range
  41260. */
  41261. RollingAverage.prototype._wrapPosition = function (i) {
  41262. var max = this._samples.length;
  41263. return ((i % max) + max) % max;
  41264. };
  41265. return RollingAverage;
  41266. }());
  41267. BABYLON.RollingAverage = RollingAverage;
  41268. })(BABYLON || (BABYLON = {}));
  41269. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41270. var BABYLON;
  41271. (function (BABYLON) {
  41272. /**
  41273. * This groups together the common properties used for image processing either in direct forward pass
  41274. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41275. * or not.
  41276. */
  41277. var ImageProcessingConfiguration = /** @class */ (function () {
  41278. function ImageProcessingConfiguration() {
  41279. /**
  41280. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41281. */
  41282. this.colorCurves = new BABYLON.ColorCurves();
  41283. this._colorCurvesEnabled = false;
  41284. this._colorGradingEnabled = false;
  41285. this._colorGradingWithGreenDepth = true;
  41286. this._colorGradingBGR = true;
  41287. this._exposure = 1.0;
  41288. this._toneMappingEnabled = false;
  41289. this._contrast = 1.0;
  41290. /**
  41291. * Vignette stretch size.
  41292. */
  41293. this.vignetteStretch = 0;
  41294. /**
  41295. * Vignette centre X Offset.
  41296. */
  41297. this.vignetteCentreX = 0;
  41298. /**
  41299. * Vignette centre Y Offset.
  41300. */
  41301. this.vignetteCentreY = 0;
  41302. /**
  41303. * Vignette weight or intensity of the vignette effect.
  41304. */
  41305. this.vignetteWeight = 1.5;
  41306. /**
  41307. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41308. * if vignetteEnabled is set to true.
  41309. */
  41310. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41311. /**
  41312. * Camera field of view used by the Vignette effect.
  41313. */
  41314. this.vignetteCameraFov = 0.5;
  41315. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41316. this._vignetteEnabled = false;
  41317. this._applyByPostProcess = false;
  41318. this._isEnabled = true;
  41319. /**
  41320. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41321. */
  41322. this.onUpdateParameters = new BABYLON.Observable();
  41323. }
  41324. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41325. /**
  41326. * Gets wether the color curves effect is enabled.
  41327. */
  41328. get: function () {
  41329. return this._colorCurvesEnabled;
  41330. },
  41331. /**
  41332. * Sets wether the color curves effect is enabled.
  41333. */
  41334. set: function (value) {
  41335. if (this._colorCurvesEnabled === value) {
  41336. return;
  41337. }
  41338. this._colorCurvesEnabled = value;
  41339. this._updateParameters();
  41340. },
  41341. enumerable: true,
  41342. configurable: true
  41343. });
  41344. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41345. /**
  41346. * Gets wether the color grading effect is enabled.
  41347. */
  41348. get: function () {
  41349. return this._colorGradingEnabled;
  41350. },
  41351. /**
  41352. * Sets wether the color grading effect is enabled.
  41353. */
  41354. set: function (value) {
  41355. if (this._colorGradingEnabled === value) {
  41356. return;
  41357. }
  41358. this._colorGradingEnabled = value;
  41359. this._updateParameters();
  41360. },
  41361. enumerable: true,
  41362. configurable: true
  41363. });
  41364. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41365. /**
  41366. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41367. */
  41368. get: function () {
  41369. return this._colorGradingWithGreenDepth;
  41370. },
  41371. /**
  41372. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41373. */
  41374. set: function (value) {
  41375. if (this._colorGradingWithGreenDepth === value) {
  41376. return;
  41377. }
  41378. this._colorGradingWithGreenDepth = value;
  41379. this._updateParameters();
  41380. },
  41381. enumerable: true,
  41382. configurable: true
  41383. });
  41384. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41385. /**
  41386. * Gets wether the color grading texture contains BGR values.
  41387. */
  41388. get: function () {
  41389. return this._colorGradingBGR;
  41390. },
  41391. /**
  41392. * Sets wether the color grading texture contains BGR values.
  41393. */
  41394. set: function (value) {
  41395. if (this._colorGradingBGR === value) {
  41396. return;
  41397. }
  41398. this._colorGradingBGR = value;
  41399. this._updateParameters();
  41400. },
  41401. enumerable: true,
  41402. configurable: true
  41403. });
  41404. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41405. /**
  41406. * Gets the Exposure used in the effect.
  41407. */
  41408. get: function () {
  41409. return this._exposure;
  41410. },
  41411. /**
  41412. * Sets the Exposure used in the effect.
  41413. */
  41414. set: function (value) {
  41415. if (this._exposure === value) {
  41416. return;
  41417. }
  41418. this._exposure = value;
  41419. this._updateParameters();
  41420. },
  41421. enumerable: true,
  41422. configurable: true
  41423. });
  41424. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41425. /**
  41426. * Gets wether the tone mapping effect is enabled.
  41427. */
  41428. get: function () {
  41429. return this._toneMappingEnabled;
  41430. },
  41431. /**
  41432. * Sets wether the tone mapping effect is enabled.
  41433. */
  41434. set: function (value) {
  41435. if (this._toneMappingEnabled === value) {
  41436. return;
  41437. }
  41438. this._toneMappingEnabled = value;
  41439. this._updateParameters();
  41440. },
  41441. enumerable: true,
  41442. configurable: true
  41443. });
  41444. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41445. /**
  41446. * Gets the contrast used in the effect.
  41447. */
  41448. get: function () {
  41449. return this._contrast;
  41450. },
  41451. /**
  41452. * Sets the contrast used in the effect.
  41453. */
  41454. set: function (value) {
  41455. if (this._contrast === value) {
  41456. return;
  41457. }
  41458. this._contrast = value;
  41459. this._updateParameters();
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41465. /**
  41466. * Gets the vignette blend mode allowing different kind of effect.
  41467. */
  41468. get: function () {
  41469. return this._vignetteBlendMode;
  41470. },
  41471. /**
  41472. * Sets the vignette blend mode allowing different kind of effect.
  41473. */
  41474. set: function (value) {
  41475. if (this._vignetteBlendMode === value) {
  41476. return;
  41477. }
  41478. this._vignetteBlendMode = value;
  41479. this._updateParameters();
  41480. },
  41481. enumerable: true,
  41482. configurable: true
  41483. });
  41484. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41485. /**
  41486. * Gets wether the vignette effect is enabled.
  41487. */
  41488. get: function () {
  41489. return this._vignetteEnabled;
  41490. },
  41491. /**
  41492. * Sets wether the vignette effect is enabled.
  41493. */
  41494. set: function (value) {
  41495. if (this._vignetteEnabled === value) {
  41496. return;
  41497. }
  41498. this._vignetteEnabled = value;
  41499. this._updateParameters();
  41500. },
  41501. enumerable: true,
  41502. configurable: true
  41503. });
  41504. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41505. /**
  41506. * Gets wether the image processing is applied through a post process or not.
  41507. */
  41508. get: function () {
  41509. return this._applyByPostProcess;
  41510. },
  41511. /**
  41512. * Sets wether the image processing is applied through a post process or not.
  41513. */
  41514. set: function (value) {
  41515. if (this._applyByPostProcess === value) {
  41516. return;
  41517. }
  41518. this._applyByPostProcess = value;
  41519. this._updateParameters();
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41525. /**
  41526. * Gets wether the image processing is enabled or not.
  41527. */
  41528. get: function () {
  41529. return this._isEnabled;
  41530. },
  41531. /**
  41532. * Sets wether the image processing is enabled or not.
  41533. */
  41534. set: function (value) {
  41535. if (this._isEnabled === value) {
  41536. return;
  41537. }
  41538. this._isEnabled = value;
  41539. this._updateParameters();
  41540. },
  41541. enumerable: true,
  41542. configurable: true
  41543. });
  41544. /**
  41545. * Method called each time the image processing information changes requires to recompile the effect.
  41546. */
  41547. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41548. this.onUpdateParameters.notifyObservers(this);
  41549. };
  41550. ImageProcessingConfiguration.prototype.getClassName = function () {
  41551. return "ImageProcessingConfiguration";
  41552. };
  41553. /**
  41554. * Prepare the list of uniforms associated with the Image Processing effects.
  41555. * @param uniformsList The list of uniforms used in the effect
  41556. * @param defines the list of defines currently in use
  41557. */
  41558. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41559. if (defines.EXPOSURE) {
  41560. uniforms.push("exposureLinear");
  41561. }
  41562. if (defines.CONTRAST) {
  41563. uniforms.push("contrast");
  41564. }
  41565. if (defines.COLORGRADING) {
  41566. uniforms.push("colorTransformSettings");
  41567. }
  41568. if (defines.VIGNETTE) {
  41569. uniforms.push("vInverseScreenSize");
  41570. uniforms.push("vignetteSettings1");
  41571. uniforms.push("vignetteSettings2");
  41572. }
  41573. if (defines.COLORCURVES) {
  41574. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41575. }
  41576. };
  41577. /**
  41578. * Prepare the list of samplers associated with the Image Processing effects.
  41579. * @param uniformsList The list of uniforms used in the effect
  41580. * @param defines the list of defines currently in use
  41581. */
  41582. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41583. if (defines.COLORGRADING) {
  41584. samplersList.push("txColorTransform");
  41585. }
  41586. };
  41587. /**
  41588. * Prepare the list of defines associated to the shader.
  41589. * @param defines the list of defines to complete
  41590. */
  41591. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41592. if (forPostProcess === void 0) { forPostProcess = false; }
  41593. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41594. defines.VIGNETTE = false;
  41595. defines.TONEMAPPING = false;
  41596. defines.CONTRAST = false;
  41597. defines.EXPOSURE = false;
  41598. defines.COLORCURVES = false;
  41599. defines.COLORGRADING = false;
  41600. defines.COLORGRADING3D = false;
  41601. defines.IMAGEPROCESSING = false;
  41602. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41603. return;
  41604. }
  41605. defines.VIGNETTE = this.vignetteEnabled;
  41606. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41607. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41608. defines.TONEMAPPING = this.toneMappingEnabled;
  41609. defines.CONTRAST = (this.contrast !== 1.0);
  41610. defines.EXPOSURE = (this.exposure !== 1.0);
  41611. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41612. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41613. if (defines.COLORGRADING) {
  41614. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41615. }
  41616. else {
  41617. defines.COLORGRADING3D = false;
  41618. }
  41619. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41620. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41621. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41622. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41623. };
  41624. /**
  41625. * Returns true if all the image processing information are ready.
  41626. */
  41627. ImageProcessingConfiguration.prototype.isReady = function () {
  41628. // Color Grading texure can not be none blocking.
  41629. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41630. };
  41631. /**
  41632. * Binds the image processing to the shader.
  41633. * @param effect The effect to bind to
  41634. */
  41635. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41636. if (aspectRatio === void 0) { aspectRatio = 1; }
  41637. // Color Curves
  41638. if (this._colorCurvesEnabled && this.colorCurves) {
  41639. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41640. }
  41641. // Vignette
  41642. if (this._vignetteEnabled) {
  41643. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41644. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41645. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41646. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41647. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41648. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41649. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41650. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41651. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41652. var vignettePower = -2.0 * this.vignetteWeight;
  41653. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41654. }
  41655. // Exposure
  41656. effect.setFloat("exposureLinear", this.exposure);
  41657. // Contrast
  41658. effect.setFloat("contrast", this.contrast);
  41659. // Color transform settings
  41660. if (this.colorGradingTexture) {
  41661. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41662. var textureSize = this.colorGradingTexture.getSize().height;
  41663. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41664. 0.5 / textureSize, // textureOffset
  41665. textureSize, // textureSize
  41666. this.colorGradingTexture.level // weight
  41667. );
  41668. }
  41669. };
  41670. /**
  41671. * Clones the current image processing instance.
  41672. * @return The cloned image processing
  41673. */
  41674. ImageProcessingConfiguration.prototype.clone = function () {
  41675. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41676. };
  41677. /**
  41678. * Serializes the current image processing instance to a json representation.
  41679. * @return a JSON representation
  41680. */
  41681. ImageProcessingConfiguration.prototype.serialize = function () {
  41682. return BABYLON.SerializationHelper.Serialize(this);
  41683. };
  41684. /**
  41685. * Parses the image processing from a json representation.
  41686. * @param source the JSON source to parse
  41687. * @return The parsed image processing
  41688. */
  41689. ImageProcessingConfiguration.Parse = function (source) {
  41690. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41691. };
  41692. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41693. /**
  41694. * Used to apply the vignette as a mix with the pixel color.
  41695. */
  41696. get: function () {
  41697. return this._VIGNETTEMODE_MULTIPLY;
  41698. },
  41699. enumerable: true,
  41700. configurable: true
  41701. });
  41702. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41703. /**
  41704. * Used to apply the vignette as a replacement of the pixel color.
  41705. */
  41706. get: function () {
  41707. return this._VIGNETTEMODE_OPAQUE;
  41708. },
  41709. enumerable: true,
  41710. configurable: true
  41711. });
  41712. // Static constants associated to the image processing.
  41713. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41714. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41715. __decorate([
  41716. BABYLON.serializeAsColorCurves()
  41717. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41718. __decorate([
  41719. BABYLON.serialize()
  41720. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41721. __decorate([
  41722. BABYLON.serializeAsTexture()
  41723. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41724. __decorate([
  41725. BABYLON.serialize()
  41726. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41727. __decorate([
  41728. BABYLON.serialize()
  41729. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41730. __decorate([
  41731. BABYLON.serialize()
  41732. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41733. __decorate([
  41734. BABYLON.serialize()
  41735. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41736. __decorate([
  41737. BABYLON.serialize()
  41738. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41739. __decorate([
  41740. BABYLON.serialize()
  41741. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41742. __decorate([
  41743. BABYLON.serialize()
  41744. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41745. __decorate([
  41746. BABYLON.serialize()
  41747. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41748. __decorate([
  41749. BABYLON.serialize()
  41750. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41751. __decorate([
  41752. BABYLON.serialize()
  41753. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41754. __decorate([
  41755. BABYLON.serializeAsColor4()
  41756. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41757. __decorate([
  41758. BABYLON.serialize()
  41759. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41760. __decorate([
  41761. BABYLON.serialize()
  41762. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41763. __decorate([
  41764. BABYLON.serialize()
  41765. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41766. __decorate([
  41767. BABYLON.serialize()
  41768. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41769. __decorate([
  41770. BABYLON.serialize()
  41771. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41772. return ImageProcessingConfiguration;
  41773. }());
  41774. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41775. })(BABYLON || (BABYLON = {}));
  41776. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41777. var BABYLON;
  41778. (function (BABYLON) {
  41779. /**
  41780. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41781. * It can help converting any input color in a desired output one. This can then be used to create effects
  41782. * from sepia, black and white to sixties or futuristic rendering...
  41783. *
  41784. * The only supported format is currently 3dl.
  41785. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41786. */
  41787. var ColorGradingTexture = /** @class */ (function (_super) {
  41788. __extends(ColorGradingTexture, _super);
  41789. /**
  41790. * Instantiates a ColorGradingTexture from the following parameters.
  41791. *
  41792. * @param url The location of the color gradind data (currently only supporting 3dl)
  41793. * @param scene The scene the texture will be used in
  41794. */
  41795. function ColorGradingTexture(url, scene) {
  41796. var _this = _super.call(this, scene) || this;
  41797. if (!url) {
  41798. return _this;
  41799. }
  41800. _this._engine = scene.getEngine();
  41801. _this._textureMatrix = BABYLON.Matrix.Identity();
  41802. _this.name = url;
  41803. _this.url = url;
  41804. _this.hasAlpha = false;
  41805. _this.isCube = false;
  41806. _this.is3D = _this._engine.webGLVersion > 1;
  41807. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41808. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41809. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41810. _this.anisotropicFilteringLevel = 1;
  41811. _this._texture = _this._getFromCache(url, true);
  41812. if (!_this._texture) {
  41813. if (!scene.useDelayedTextureLoading) {
  41814. _this.loadTexture();
  41815. }
  41816. else {
  41817. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41818. }
  41819. }
  41820. return _this;
  41821. }
  41822. /**
  41823. * Returns the texture matrix used in most of the material.
  41824. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41825. */
  41826. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41827. return this._textureMatrix;
  41828. };
  41829. /**
  41830. * Occurs when the file being loaded is a .3dl LUT file.
  41831. */
  41832. ColorGradingTexture.prototype.load3dlTexture = function () {
  41833. var engine = this._engine;
  41834. var texture;
  41835. if (engine.webGLVersion === 1) {
  41836. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41837. }
  41838. else {
  41839. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41840. }
  41841. this._texture = texture;
  41842. var callback = function (text) {
  41843. if (typeof text !== "string") {
  41844. return;
  41845. }
  41846. var data = null;
  41847. var tempData = null;
  41848. var line;
  41849. var lines = text.split('\n');
  41850. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41851. var maxColor = 0;
  41852. for (var i = 0; i < lines.length; i++) {
  41853. line = lines[i];
  41854. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41855. continue;
  41856. if (line.indexOf('#') === 0)
  41857. continue;
  41858. var words = line.split(" ");
  41859. if (size === 0) {
  41860. // Number of space + one
  41861. size = words.length;
  41862. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41863. tempData = new Float32Array(size * size * size * 4);
  41864. continue;
  41865. }
  41866. if (size != 0) {
  41867. var r = Math.max(parseInt(words[0]), 0);
  41868. var g = Math.max(parseInt(words[1]), 0);
  41869. var b = Math.max(parseInt(words[2]), 0);
  41870. maxColor = Math.max(r, maxColor);
  41871. maxColor = Math.max(g, maxColor);
  41872. maxColor = Math.max(b, maxColor);
  41873. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41874. if (tempData) {
  41875. tempData[pixelStorageIndex + 0] = r;
  41876. tempData[pixelStorageIndex + 1] = g;
  41877. tempData[pixelStorageIndex + 2] = b;
  41878. }
  41879. pixelIndexSlice++;
  41880. if (pixelIndexSlice % size == 0) {
  41881. pixelIndexH++;
  41882. pixelIndexSlice = 0;
  41883. if (pixelIndexH % size == 0) {
  41884. pixelIndexW++;
  41885. pixelIndexH = 0;
  41886. }
  41887. }
  41888. }
  41889. }
  41890. if (tempData && data) {
  41891. for (var i = 0; i < tempData.length; i++) {
  41892. if (i > 0 && (i + 1) % 4 === 0) {
  41893. data[i] = 255;
  41894. }
  41895. else {
  41896. var value = tempData[i];
  41897. data[i] = (value / maxColor * 255);
  41898. }
  41899. }
  41900. }
  41901. if (texture.is3D) {
  41902. texture.updateSize(size, size, size);
  41903. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41904. }
  41905. else {
  41906. texture.updateSize(size * size, size);
  41907. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41908. }
  41909. };
  41910. var scene = this.getScene();
  41911. if (scene) {
  41912. scene._loadFile(this.url, callback);
  41913. }
  41914. else {
  41915. this._engine._loadFile(this.url, callback);
  41916. }
  41917. return this._texture;
  41918. };
  41919. /**
  41920. * Starts the loading process of the texture.
  41921. */
  41922. ColorGradingTexture.prototype.loadTexture = function () {
  41923. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41924. this.load3dlTexture();
  41925. }
  41926. };
  41927. /**
  41928. * Clones the color gradind texture.
  41929. */
  41930. ColorGradingTexture.prototype.clone = function () {
  41931. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41932. // Base texture
  41933. newTexture.level = this.level;
  41934. return newTexture;
  41935. };
  41936. /**
  41937. * Called during delayed load for textures.
  41938. */
  41939. ColorGradingTexture.prototype.delayLoad = function () {
  41940. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41941. return;
  41942. }
  41943. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41944. this._texture = this._getFromCache(this.url, true);
  41945. if (!this._texture) {
  41946. this.loadTexture();
  41947. }
  41948. };
  41949. /**
  41950. * Parses a color grading texture serialized by Babylon.
  41951. * @param parsedTexture The texture information being parsedTexture
  41952. * @param scene The scene to load the texture in
  41953. * @param rootUrl The root url of the data assets to load
  41954. * @return A color gradind texture
  41955. */
  41956. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41957. var texture = null;
  41958. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41959. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41960. texture.name = parsedTexture.name;
  41961. texture.level = parsedTexture.level;
  41962. }
  41963. return texture;
  41964. };
  41965. /**
  41966. * Serializes the LUT texture to json format.
  41967. */
  41968. ColorGradingTexture.prototype.serialize = function () {
  41969. if (!this.name) {
  41970. return null;
  41971. }
  41972. var serializationObject = {};
  41973. serializationObject.name = this.name;
  41974. serializationObject.level = this.level;
  41975. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41976. return serializationObject;
  41977. };
  41978. /**
  41979. * Empty line regex stored for GC.
  41980. */
  41981. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41982. return ColorGradingTexture;
  41983. }(BABYLON.BaseTexture));
  41984. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41985. })(BABYLON || (BABYLON = {}));
  41986. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41987. var BABYLON;
  41988. (function (BABYLON) {
  41989. /**
  41990. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41991. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41992. * 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;
  41993. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41994. */
  41995. var ColorCurves = /** @class */ (function () {
  41996. function ColorCurves() {
  41997. this._dirty = true;
  41998. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41999. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  42000. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42001. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  42002. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  42003. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  42004. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  42005. this._globalHue = 30;
  42006. this._globalDensity = 0;
  42007. this._globalSaturation = 0;
  42008. this._globalExposure = 0;
  42009. this._highlightsHue = 30;
  42010. this._highlightsDensity = 0;
  42011. this._highlightsSaturation = 0;
  42012. this._highlightsExposure = 0;
  42013. this._midtonesHue = 30;
  42014. this._midtonesDensity = 0;
  42015. this._midtonesSaturation = 0;
  42016. this._midtonesExposure = 0;
  42017. this._shadowsHue = 30;
  42018. this._shadowsDensity = 0;
  42019. this._shadowsSaturation = 0;
  42020. this._shadowsExposure = 0;
  42021. }
  42022. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  42023. /**
  42024. * Gets the global Hue value.
  42025. * 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).
  42026. */
  42027. get: function () {
  42028. return this._globalHue;
  42029. },
  42030. /**
  42031. * Sets the global Hue value.
  42032. * 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).
  42033. */
  42034. set: function (value) {
  42035. this._globalHue = value;
  42036. this._dirty = true;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  42042. /**
  42043. * Gets the global Density value.
  42044. * 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.
  42045. * Values less than zero provide a filter of opposite hue.
  42046. */
  42047. get: function () {
  42048. return this._globalDensity;
  42049. },
  42050. /**
  42051. * Sets the global Density value.
  42052. * 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.
  42053. * Values less than zero provide a filter of opposite hue.
  42054. */
  42055. set: function (value) {
  42056. this._globalDensity = value;
  42057. this._dirty = true;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42063. /**
  42064. * Gets the global Saturation value.
  42065. * 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.
  42066. */
  42067. get: function () {
  42068. return this._globalSaturation;
  42069. },
  42070. /**
  42071. * Sets the global Saturation value.
  42072. * 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.
  42073. */
  42074. set: function (value) {
  42075. this._globalSaturation = value;
  42076. this._dirty = true;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42082. /**
  42083. * Gets the global Exposure 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 exposure and negative values decrease exposure.
  42085. */
  42086. get: function () {
  42087. return this._globalExposure;
  42088. },
  42089. /**
  42090. * Sets the global Exposure value.
  42091. * 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.
  42092. */
  42093. set: function (value) {
  42094. this._globalExposure = value;
  42095. this._dirty = true;
  42096. },
  42097. enumerable: true,
  42098. configurable: true
  42099. });
  42100. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42101. /**
  42102. * Gets the highlights Hue value.
  42103. * 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).
  42104. */
  42105. get: function () {
  42106. return this._highlightsHue;
  42107. },
  42108. /**
  42109. * Sets the highlights Hue value.
  42110. * 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).
  42111. */
  42112. set: function (value) {
  42113. this._highlightsHue = value;
  42114. this._dirty = true;
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42120. /**
  42121. * Gets the highlights Density value.
  42122. * 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.
  42123. * Values less than zero provide a filter of opposite hue.
  42124. */
  42125. get: function () {
  42126. return this._highlightsDensity;
  42127. },
  42128. /**
  42129. * Sets the highlights Density value.
  42130. * 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.
  42131. * Values less than zero provide a filter of opposite hue.
  42132. */
  42133. set: function (value) {
  42134. this._highlightsDensity = value;
  42135. this._dirty = true;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42141. /**
  42142. * Gets the highlights Saturation value.
  42143. * 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.
  42144. */
  42145. get: function () {
  42146. return this._highlightsSaturation;
  42147. },
  42148. /**
  42149. * Sets the highlights Saturation value.
  42150. * 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.
  42151. */
  42152. set: function (value) {
  42153. this._highlightsSaturation = value;
  42154. this._dirty = true;
  42155. },
  42156. enumerable: true,
  42157. configurable: true
  42158. });
  42159. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42160. /**
  42161. * Gets the highlights Exposure 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 exposure and negative values decrease exposure.
  42163. */
  42164. get: function () {
  42165. return this._highlightsExposure;
  42166. },
  42167. /**
  42168. * Sets the highlights Exposure value.
  42169. * 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.
  42170. */
  42171. set: function (value) {
  42172. this._highlightsExposure = value;
  42173. this._dirty = true;
  42174. },
  42175. enumerable: true,
  42176. configurable: true
  42177. });
  42178. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42179. /**
  42180. * Gets the midtones Hue value.
  42181. * 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).
  42182. */
  42183. get: function () {
  42184. return this._midtonesHue;
  42185. },
  42186. /**
  42187. * Sets the midtones Hue value.
  42188. * 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).
  42189. */
  42190. set: function (value) {
  42191. this._midtonesHue = value;
  42192. this._dirty = true;
  42193. },
  42194. enumerable: true,
  42195. configurable: true
  42196. });
  42197. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42198. /**
  42199. * Gets the midtones Density value.
  42200. * 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.
  42201. * Values less than zero provide a filter of opposite hue.
  42202. */
  42203. get: function () {
  42204. return this._midtonesDensity;
  42205. },
  42206. /**
  42207. * Sets the midtones Density value.
  42208. * 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.
  42209. * Values less than zero provide a filter of opposite hue.
  42210. */
  42211. set: function (value) {
  42212. this._midtonesDensity = value;
  42213. this._dirty = true;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42219. /**
  42220. * Gets the midtones Saturation value.
  42221. * 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.
  42222. */
  42223. get: function () {
  42224. return this._midtonesSaturation;
  42225. },
  42226. /**
  42227. * Sets the midtones Saturation value.
  42228. * 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.
  42229. */
  42230. set: function (value) {
  42231. this._midtonesSaturation = value;
  42232. this._dirty = true;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42238. /**
  42239. * Gets the midtones Exposure 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 exposure and negative values decrease exposure.
  42241. */
  42242. get: function () {
  42243. return this._midtonesExposure;
  42244. },
  42245. /**
  42246. * Sets the midtones Exposure value.
  42247. * 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.
  42248. */
  42249. set: function (value) {
  42250. this._midtonesExposure = value;
  42251. this._dirty = true;
  42252. },
  42253. enumerable: true,
  42254. configurable: true
  42255. });
  42256. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42257. /**
  42258. * Gets the shadows Hue value.
  42259. * 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).
  42260. */
  42261. get: function () {
  42262. return this._shadowsHue;
  42263. },
  42264. /**
  42265. * Sets the shadows Hue value.
  42266. * 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).
  42267. */
  42268. set: function (value) {
  42269. this._shadowsHue = value;
  42270. this._dirty = true;
  42271. },
  42272. enumerable: true,
  42273. configurable: true
  42274. });
  42275. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42276. /**
  42277. * Gets the shadows Density value.
  42278. * 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.
  42279. * Values less than zero provide a filter of opposite hue.
  42280. */
  42281. get: function () {
  42282. return this._shadowsDensity;
  42283. },
  42284. /**
  42285. * Sets the shadows Density value.
  42286. * 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.
  42287. * Values less than zero provide a filter of opposite hue.
  42288. */
  42289. set: function (value) {
  42290. this._shadowsDensity = value;
  42291. this._dirty = true;
  42292. },
  42293. enumerable: true,
  42294. configurable: true
  42295. });
  42296. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42297. /**
  42298. * Gets the shadows Saturation value.
  42299. * 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.
  42300. */
  42301. get: function () {
  42302. return this._shadowsSaturation;
  42303. },
  42304. /**
  42305. * Sets the shadows Saturation value.
  42306. * 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.
  42307. */
  42308. set: function (value) {
  42309. this._shadowsSaturation = value;
  42310. this._dirty = true;
  42311. },
  42312. enumerable: true,
  42313. configurable: true
  42314. });
  42315. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42316. /**
  42317. * Gets the shadows Exposure 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 exposure and negative values decrease exposure.
  42319. */
  42320. get: function () {
  42321. return this._shadowsExposure;
  42322. },
  42323. /**
  42324. * Sets the shadows Exposure value.
  42325. * 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.
  42326. */
  42327. set: function (value) {
  42328. this._shadowsExposure = value;
  42329. this._dirty = true;
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. ColorCurves.prototype.getClassName = function () {
  42335. return "ColorCurves";
  42336. };
  42337. /**
  42338. * Binds the color curves to the shader.
  42339. * @param colorCurves The color curve to bind
  42340. * @param effect The effect to bind to
  42341. */
  42342. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42343. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42344. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42345. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42346. if (colorCurves._dirty) {
  42347. colorCurves._dirty = false;
  42348. // Fill in global info.
  42349. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42350. // Compute highlights info.
  42351. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42352. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42353. // Compute midtones info.
  42354. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42355. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42356. // Compute shadows info.
  42357. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42358. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42359. // Compute deltas (neutral is midtones).
  42360. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42361. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42362. }
  42363. if (effect) {
  42364. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42365. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42366. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42367. }
  42368. };
  42369. /**
  42370. * Prepare the list of uniforms associated with the ColorCurves effects.
  42371. * @param uniformsList The list of uniforms used in the effect
  42372. */
  42373. ColorCurves.PrepareUniforms = function (uniformsList) {
  42374. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42375. };
  42376. /**
  42377. * Returns color grading data based on a hue, density, saturation and exposure value.
  42378. * @param filterHue The hue of the color filter.
  42379. * @param filterDensity The density of the color filter.
  42380. * @param saturation The saturation.
  42381. * @param exposure The exposure.
  42382. * @param result The result data container.
  42383. */
  42384. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42385. if (hue == null) {
  42386. return;
  42387. }
  42388. hue = ColorCurves.clamp(hue, 0, 360);
  42389. density = ColorCurves.clamp(density, -100, 100);
  42390. saturation = ColorCurves.clamp(saturation, -100, 100);
  42391. exposure = ColorCurves.clamp(exposure, -100, 100);
  42392. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42393. // so that the maximum filter density is only 50% control. This provides fine control
  42394. // for small values and reasonable range.
  42395. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42396. density *= 0.5;
  42397. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42398. if (density < 0) {
  42399. density *= -1;
  42400. hue = (hue + 180) % 360;
  42401. }
  42402. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42403. result.scaleToRef(2, result);
  42404. result.a = 1 + 0.01 * saturation;
  42405. };
  42406. /**
  42407. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42408. * @param value The input slider value in range [-100,100].
  42409. * @returns Adjusted value.
  42410. */
  42411. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42412. value /= 100;
  42413. var x = Math.abs(value);
  42414. x = Math.pow(x, 2);
  42415. if (value < 0) {
  42416. x *= -1;
  42417. }
  42418. x *= 100;
  42419. return x;
  42420. };
  42421. /**
  42422. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42423. * @param hue The hue (H) input.
  42424. * @param saturation The saturation (S) input.
  42425. * @param brightness The brightness (B) input.
  42426. * @result An RGBA color represented as Vector4.
  42427. */
  42428. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42429. var h = ColorCurves.clamp(hue, 0, 360);
  42430. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42431. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42432. if (s === 0) {
  42433. result.r = v;
  42434. result.g = v;
  42435. result.b = v;
  42436. }
  42437. else {
  42438. // sector 0 to 5
  42439. h /= 60;
  42440. var i = Math.floor(h);
  42441. // fractional part of h
  42442. var f = h - i;
  42443. var p = v * (1 - s);
  42444. var q = v * (1 - s * f);
  42445. var t = v * (1 - s * (1 - f));
  42446. switch (i) {
  42447. case 0:
  42448. result.r = v;
  42449. result.g = t;
  42450. result.b = p;
  42451. break;
  42452. case 1:
  42453. result.r = q;
  42454. result.g = v;
  42455. result.b = p;
  42456. break;
  42457. case 2:
  42458. result.r = p;
  42459. result.g = v;
  42460. result.b = t;
  42461. break;
  42462. case 3:
  42463. result.r = p;
  42464. result.g = q;
  42465. result.b = v;
  42466. break;
  42467. case 4:
  42468. result.r = t;
  42469. result.g = p;
  42470. result.b = v;
  42471. break;
  42472. default: // case 5:
  42473. result.r = v;
  42474. result.g = p;
  42475. result.b = q;
  42476. break;
  42477. }
  42478. }
  42479. result.a = 1;
  42480. };
  42481. /**
  42482. * Returns a value clamped between min and max
  42483. * @param value The value to clamp
  42484. * @param min The minimum of value
  42485. * @param max The maximum of value
  42486. * @returns The clamped value.
  42487. */
  42488. ColorCurves.clamp = function (value, min, max) {
  42489. return Math.min(Math.max(value, min), max);
  42490. };
  42491. /**
  42492. * Clones the current color curve instance.
  42493. * @return The cloned curves
  42494. */
  42495. ColorCurves.prototype.clone = function () {
  42496. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42497. };
  42498. /**
  42499. * Serializes the current color curve instance to a json representation.
  42500. * @return a JSON representation
  42501. */
  42502. ColorCurves.prototype.serialize = function () {
  42503. return BABYLON.SerializationHelper.Serialize(this);
  42504. };
  42505. /**
  42506. * Parses the color curve from a json representation.
  42507. * @param source the JSON source to parse
  42508. * @return The parsed curves
  42509. */
  42510. ColorCurves.Parse = function (source) {
  42511. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42512. };
  42513. __decorate([
  42514. BABYLON.serialize()
  42515. ], ColorCurves.prototype, "_globalHue", void 0);
  42516. __decorate([
  42517. BABYLON.serialize()
  42518. ], ColorCurves.prototype, "_globalDensity", void 0);
  42519. __decorate([
  42520. BABYLON.serialize()
  42521. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42522. __decorate([
  42523. BABYLON.serialize()
  42524. ], ColorCurves.prototype, "_globalExposure", void 0);
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42528. __decorate([
  42529. BABYLON.serialize()
  42530. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42531. __decorate([
  42532. BABYLON.serialize()
  42533. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42534. __decorate([
  42535. BABYLON.serialize()
  42536. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42537. __decorate([
  42538. BABYLON.serialize()
  42539. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42540. __decorate([
  42541. BABYLON.serialize()
  42542. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42543. __decorate([
  42544. BABYLON.serialize()
  42545. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42546. __decorate([
  42547. BABYLON.serialize()
  42548. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42549. return ColorCurves;
  42550. }());
  42551. BABYLON.ColorCurves = ColorCurves;
  42552. })(BABYLON || (BABYLON = {}));
  42553. //# sourceMappingURL=babylon.colorCurves.js.map
  42554. //# sourceMappingURL=babylon.behavior.js.map
  42555. var BABYLON;
  42556. (function (BABYLON) {
  42557. /**
  42558. * "Static Class" containing the most commonly used helper while dealing with material for
  42559. * rendering purpose.
  42560. *
  42561. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42562. *
  42563. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42564. */
  42565. var MaterialHelper = /** @class */ (function () {
  42566. function MaterialHelper() {
  42567. }
  42568. /**
  42569. * Bind the current view position to an effect.
  42570. * @param effect The effect to be bound
  42571. * @param scene The scene the eyes position is used from
  42572. */
  42573. MaterialHelper.BindEyePosition = function (effect, scene) {
  42574. if (scene._forcedViewPosition) {
  42575. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42576. return;
  42577. }
  42578. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42579. };
  42580. /**
  42581. * Helps preparing the defines values about the UVs in used in the effect.
  42582. * UVs are shared as much as we can accross chanels in the shaders.
  42583. * @param texture The texture we are preparing the UVs for
  42584. * @param defines The defines to update
  42585. * @param key The chanel key "diffuse", "specular"... used in the shader
  42586. */
  42587. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42588. defines._needUVs = true;
  42589. defines[key] = true;
  42590. if (texture.getTextureMatrix().isIdentity(true)) {
  42591. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42592. if (texture.coordinatesIndex === 0) {
  42593. defines["MAINUV1"] = true;
  42594. }
  42595. else {
  42596. defines["MAINUV2"] = true;
  42597. }
  42598. }
  42599. else {
  42600. defines[key + "DIRECTUV"] = 0;
  42601. }
  42602. };
  42603. /**
  42604. * Binds a texture matrix value to its corrsponding uniform
  42605. * @param texture The texture to bind the matrix for
  42606. * @param uniformBuffer The uniform buffer receivin the data
  42607. * @param key The chanel key "diffuse", "specular"... used in the shader
  42608. */
  42609. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42610. var matrix = texture.getTextureMatrix();
  42611. if (!matrix.isIdentity(true)) {
  42612. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42613. }
  42614. };
  42615. /**
  42616. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42617. * @param mesh defines the current mesh
  42618. * @param scene defines the current scene
  42619. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42620. * @param pointsCloud defines if point cloud rendering has to be turned on
  42621. * @param fogEnabled defines if fog has to be turned on
  42622. * @param alphaTest defines if alpha testing has to be turned on
  42623. * @param defines defines the current list of defines
  42624. */
  42625. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42626. if (defines._areMiscDirty) {
  42627. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42628. defines["POINTSIZE"] = pointsCloud;
  42629. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42630. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42631. defines["ALPHATEST"] = alphaTest;
  42632. }
  42633. };
  42634. /**
  42635. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42636. * @param scene defines the current scene
  42637. * @param engine defines the current engine
  42638. * @param defines specifies the list of active defines
  42639. * @param useInstances defines if instances have to be turned on
  42640. * @param useClipPlane defines if clip plane have to be turned on
  42641. */
  42642. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42643. if (useClipPlane === void 0) { useClipPlane = null; }
  42644. var changed = false;
  42645. if (useClipPlane == null) {
  42646. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42647. }
  42648. if (defines["CLIPPLANE"] !== useClipPlane) {
  42649. defines["CLIPPLANE"] = useClipPlane;
  42650. changed = true;
  42651. }
  42652. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42653. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42654. changed = true;
  42655. }
  42656. if (defines["INSTANCES"] !== useInstances) {
  42657. defines["INSTANCES"] = useInstances;
  42658. changed = true;
  42659. }
  42660. if (changed) {
  42661. defines.markAsUnprocessed();
  42662. }
  42663. };
  42664. /**
  42665. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42666. * @param mesh The mesh containing the geometry data we will draw
  42667. * @param defines The defines to update
  42668. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42669. * @param useBones Precise whether bones should be used or not (override mesh info)
  42670. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42671. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42672. * @returns false if defines are considered not dirty and have not been checked
  42673. */
  42674. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42675. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42676. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42677. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42678. return false;
  42679. }
  42680. defines._normals = defines._needNormals;
  42681. defines._uvs = defines._needUVs;
  42682. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42683. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42684. defines["TANGENT"] = true;
  42685. }
  42686. if (defines._needUVs) {
  42687. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42688. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42689. }
  42690. else {
  42691. defines["UV1"] = false;
  42692. defines["UV2"] = false;
  42693. }
  42694. if (useVertexColor) {
  42695. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42696. defines["VERTEXCOLOR"] = hasVertexColors;
  42697. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42698. }
  42699. if (useBones) {
  42700. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42701. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42702. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42703. }
  42704. else {
  42705. defines["NUM_BONE_INFLUENCERS"] = 0;
  42706. defines["BonesPerMesh"] = 0;
  42707. }
  42708. }
  42709. if (useMorphTargets) {
  42710. var manager = mesh.morphTargetManager;
  42711. if (manager) {
  42712. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42713. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42714. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42715. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42716. }
  42717. else {
  42718. defines["MORPHTARGETS_TANGENT"] = false;
  42719. defines["MORPHTARGETS_NORMAL"] = false;
  42720. defines["MORPHTARGETS"] = false;
  42721. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42722. }
  42723. }
  42724. return true;
  42725. };
  42726. /**
  42727. * Prepares the defines related to the light information passed in parameter
  42728. * @param scene The scene we are intending to draw
  42729. * @param mesh The mesh the effect is compiling for
  42730. * @param defines The defines to update
  42731. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42732. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42733. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42734. * @returns true if normals will be required for the rest of the effect
  42735. */
  42736. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42737. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42738. if (disableLighting === void 0) { disableLighting = false; }
  42739. if (!defines._areLightsDirty) {
  42740. return defines._needNormals;
  42741. }
  42742. var lightIndex = 0;
  42743. var needNormals = false;
  42744. var needRebuild = false;
  42745. var lightmapMode = false;
  42746. var shadowEnabled = false;
  42747. var specularEnabled = false;
  42748. if (scene.lightsEnabled && !disableLighting) {
  42749. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42750. var light = _a[_i];
  42751. needNormals = true;
  42752. if (defines["LIGHT" + lightIndex] === undefined) {
  42753. needRebuild = true;
  42754. }
  42755. defines["LIGHT" + lightIndex] = true;
  42756. defines["SPOTLIGHT" + lightIndex] = false;
  42757. defines["HEMILIGHT" + lightIndex] = false;
  42758. defines["POINTLIGHT" + lightIndex] = false;
  42759. defines["DIRLIGHT" + lightIndex] = false;
  42760. var type;
  42761. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42762. type = "SPOTLIGHT" + lightIndex;
  42763. var spotLight = light;
  42764. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42765. }
  42766. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42767. type = "HEMILIGHT" + lightIndex;
  42768. }
  42769. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42770. type = "POINTLIGHT" + lightIndex;
  42771. }
  42772. else {
  42773. type = "DIRLIGHT" + lightIndex;
  42774. }
  42775. defines[type] = true;
  42776. // Specular
  42777. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42778. specularEnabled = true;
  42779. }
  42780. // Shadows
  42781. defines["SHADOW" + lightIndex] = false;
  42782. defines["SHADOWPCF" + lightIndex] = false;
  42783. defines["SHADOWPCSS" + lightIndex] = false;
  42784. defines["SHADOWPOISSON" + lightIndex] = false;
  42785. defines["SHADOWESM" + lightIndex] = false;
  42786. defines["SHADOWCUBE" + lightIndex] = false;
  42787. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42788. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42789. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42790. var shadowGenerator = light.getShadowGenerator();
  42791. if (shadowGenerator) {
  42792. shadowEnabled = true;
  42793. shadowGenerator.prepareDefines(defines, lightIndex);
  42794. }
  42795. }
  42796. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42797. lightmapMode = true;
  42798. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42799. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42800. }
  42801. else {
  42802. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42803. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42804. }
  42805. lightIndex++;
  42806. if (lightIndex === maxSimultaneousLights)
  42807. break;
  42808. }
  42809. }
  42810. defines["SPECULARTERM"] = specularEnabled;
  42811. defines["SHADOWS"] = shadowEnabled;
  42812. // Resetting all other lights if any
  42813. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42814. if (defines["LIGHT" + index] !== undefined) {
  42815. defines["LIGHT" + index] = false;
  42816. defines["HEMILIGHT" + lightIndex] = false;
  42817. defines["POINTLIGHT" + lightIndex] = false;
  42818. defines["DIRLIGHT" + lightIndex] = false;
  42819. defines["SPOTLIGHT" + lightIndex] = false;
  42820. defines["SHADOW" + lightIndex] = false;
  42821. }
  42822. }
  42823. var caps = scene.getEngine().getCaps();
  42824. if (defines["SHADOWFLOAT"] === undefined) {
  42825. needRebuild = true;
  42826. }
  42827. defines["SHADOWFLOAT"] = shadowEnabled &&
  42828. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42829. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42830. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42831. if (needRebuild) {
  42832. defines.rebuild();
  42833. }
  42834. return needNormals;
  42835. };
  42836. /**
  42837. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42838. * that won t be acctive due to defines being turned off.
  42839. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42840. * @param samplersList The samplers list
  42841. * @param defines The defines helping in the list generation
  42842. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42843. */
  42844. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42845. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42846. var uniformsList;
  42847. var uniformBuffersList = null;
  42848. if (uniformsListOrOptions.uniformsNames) {
  42849. var options = uniformsListOrOptions;
  42850. uniformsList = options.uniformsNames;
  42851. uniformBuffersList = options.uniformBuffersNames;
  42852. samplersList = options.samplers;
  42853. defines = options.defines;
  42854. maxSimultaneousLights = options.maxSimultaneousLights;
  42855. }
  42856. else {
  42857. uniformsList = uniformsListOrOptions;
  42858. if (!samplersList) {
  42859. samplersList = [];
  42860. }
  42861. }
  42862. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42863. if (!defines["LIGHT" + lightIndex]) {
  42864. break;
  42865. }
  42866. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42867. if (uniformBuffersList) {
  42868. uniformBuffersList.push("Light" + lightIndex);
  42869. }
  42870. samplersList.push("shadowSampler" + lightIndex);
  42871. samplersList.push("depthSampler" + lightIndex);
  42872. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42873. samplersList.push("projectionLightSampler" + lightIndex);
  42874. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42875. }
  42876. }
  42877. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42878. uniformsList.push("morphTargetInfluences");
  42879. }
  42880. };
  42881. /**
  42882. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42883. * @param defines The defines to update while falling back
  42884. * @param fallbacks The authorized effect fallbacks
  42885. * @param maxSimultaneousLights The maximum number of lights allowed
  42886. * @param rank the current rank of the Effect
  42887. * @returns The newly affected rank
  42888. */
  42889. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42890. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42891. if (rank === void 0) { rank = 0; }
  42892. var lightFallbackRank = 0;
  42893. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42894. if (!defines["LIGHT" + lightIndex]) {
  42895. break;
  42896. }
  42897. if (lightIndex > 0) {
  42898. lightFallbackRank = rank + lightIndex;
  42899. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42900. }
  42901. if (!defines["SHADOWS"]) {
  42902. if (defines["SHADOW" + lightIndex]) {
  42903. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42904. }
  42905. if (defines["SHADOWPCF" + lightIndex]) {
  42906. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42907. }
  42908. if (defines["SHADOWPCSS" + lightIndex]) {
  42909. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42910. }
  42911. if (defines["SHADOWPOISSON" + lightIndex]) {
  42912. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42913. }
  42914. if (defines["SHADOWESM" + lightIndex]) {
  42915. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42916. }
  42917. }
  42918. }
  42919. return lightFallbackRank++;
  42920. };
  42921. /**
  42922. * Prepares the list of attributes required for morph targets according to the effect defines.
  42923. * @param attribs The current list of supported attribs
  42924. * @param mesh The mesh to prepare the morph targets attributes for
  42925. * @param defines The current Defines of the effect
  42926. */
  42927. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42928. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42929. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42930. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42931. var manager = mesh.morphTargetManager;
  42932. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42933. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42934. for (var index = 0; index < influencers; index++) {
  42935. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42936. if (normal) {
  42937. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42938. }
  42939. if (tangent) {
  42940. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42941. }
  42942. if (attribs.length > maxAttributesCount) {
  42943. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42944. }
  42945. }
  42946. }
  42947. };
  42948. /**
  42949. * Prepares the list of attributes required for bones according to the effect defines.
  42950. * @param attribs The current list of supported attribs
  42951. * @param mesh The mesh to prepare the bones attributes for
  42952. * @param defines The current Defines of the effect
  42953. * @param fallbacks The current efffect fallback strategy
  42954. */
  42955. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42956. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42957. fallbacks.addCPUSkinningFallback(0, mesh);
  42958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42960. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42961. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42962. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42963. }
  42964. }
  42965. };
  42966. /**
  42967. * Prepares the list of attributes required for instances according to the effect defines.
  42968. * @param attribs The current list of supported attribs
  42969. * @param defines The current Defines of the effect
  42970. */
  42971. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42972. if (defines["INSTANCES"]) {
  42973. attribs.push("world0");
  42974. attribs.push("world1");
  42975. attribs.push("world2");
  42976. attribs.push("world3");
  42977. }
  42978. };
  42979. /**
  42980. * Binds the light shadow information to the effect for the given mesh.
  42981. * @param light The light containing the generator
  42982. * @param scene The scene the lights belongs to
  42983. * @param mesh The mesh we are binding the information to render
  42984. * @param lightIndex The light index in the effect used to render the mesh
  42985. * @param effect The effect we are binding the data to
  42986. */
  42987. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42988. if (light.shadowEnabled && mesh.receiveShadows) {
  42989. var shadowGenerator = light.getShadowGenerator();
  42990. if (shadowGenerator) {
  42991. shadowGenerator.bindShadowLight(lightIndex, effect);
  42992. }
  42993. }
  42994. };
  42995. /**
  42996. * Binds the light information to the effect.
  42997. * @param light The light containing the generator
  42998. * @param effect The effect we are binding the data to
  42999. * @param lightIndex The light index in the effect used to render
  43000. */
  43001. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43002. light.transferToEffect(effect, lightIndex + "");
  43003. };
  43004. /**
  43005. * Binds the lights information from the scene to the effect for the given mesh.
  43006. * @param scene The scene the lights belongs to
  43007. * @param mesh The mesh we are binding the information to render
  43008. * @param effect The effect we are binding the data to
  43009. * @param defines The generated defines for the effect
  43010. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43011. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43012. */
  43013. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43014. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43015. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43016. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43017. for (var i = 0; i < len; i++) {
  43018. var light = mesh._lightSources[i];
  43019. var iAsString = i.toString();
  43020. var scaledIntensity = light.getScaledIntensity();
  43021. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43022. MaterialHelper.BindLightProperties(light, effect, i);
  43023. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43024. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43025. if (defines["SPECULARTERM"]) {
  43026. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43027. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43028. }
  43029. // Shadows
  43030. if (scene.shadowsEnabled) {
  43031. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43032. }
  43033. light._uniformBuffer.update();
  43034. }
  43035. };
  43036. /**
  43037. * Binds the fog information from the scene to the effect for the given mesh.
  43038. * @param scene The scene the lights belongs to
  43039. * @param mesh The mesh we are binding the information to render
  43040. * @param effect The effect we are binding the data to
  43041. */
  43042. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  43043. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43044. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43045. effect.setColor3("vFogColor", scene.fogColor);
  43046. }
  43047. };
  43048. /**
  43049. * Binds the bones information from the mesh to the effect.
  43050. * @param mesh The mesh we are binding the information to render
  43051. * @param effect The effect we are binding the data to
  43052. */
  43053. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43054. if (!effect || !mesh) {
  43055. return;
  43056. }
  43057. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43058. mesh.computeBonesUsingShaders = false;
  43059. }
  43060. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43061. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43062. if (matrices) {
  43063. effect.setMatrices("mBones", matrices);
  43064. }
  43065. }
  43066. };
  43067. /**
  43068. * Binds the morph targets information from the mesh to the effect.
  43069. * @param abstractMesh The mesh we are binding the information to render
  43070. * @param effect The effect we are binding the data to
  43071. */
  43072. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43073. var manager = abstractMesh.morphTargetManager;
  43074. if (!abstractMesh || !manager) {
  43075. return;
  43076. }
  43077. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43078. };
  43079. /**
  43080. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43081. * @param defines The generated defines used in the effect
  43082. * @param effect The effect we are binding the data to
  43083. * @param scene The scene we are willing to render with logarithmic scale for
  43084. */
  43085. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43086. if (defines["LOGARITHMICDEPTH"]) {
  43087. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43088. }
  43089. };
  43090. /**
  43091. * Binds the clip plane information from the scene to the effect.
  43092. * @param scene The scene the clip plane information are extracted from
  43093. * @param effect The effect we are binding the data to
  43094. */
  43095. MaterialHelper.BindClipPlane = function (effect, scene) {
  43096. if (scene.clipPlane) {
  43097. var clipPlane = scene.clipPlane;
  43098. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43099. }
  43100. };
  43101. return MaterialHelper;
  43102. }());
  43103. BABYLON.MaterialHelper = MaterialHelper;
  43104. })(BABYLON || (BABYLON = {}));
  43105. //# sourceMappingURL=babylon.materialHelper.js.map
  43106. var BABYLON;
  43107. (function (BABYLON) {
  43108. var PushMaterial = /** @class */ (function (_super) {
  43109. __extends(PushMaterial, _super);
  43110. function PushMaterial(name, scene) {
  43111. var _this = _super.call(this, name, scene) || this;
  43112. _this._normalMatrix = new BABYLON.Matrix();
  43113. _this.storeEffectOnSubMeshes = true;
  43114. return _this;
  43115. }
  43116. PushMaterial.prototype.getEffect = function () {
  43117. return this._activeEffect;
  43118. };
  43119. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43120. if (!mesh) {
  43121. return false;
  43122. }
  43123. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43124. return true;
  43125. }
  43126. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43127. };
  43128. /**
  43129. * Binds the given world matrix to the active effect
  43130. *
  43131. * @param world the matrix to bind
  43132. */
  43133. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43134. this._activeEffect.setMatrix("world", world);
  43135. };
  43136. /**
  43137. * Binds the given normal matrix to the active effect
  43138. *
  43139. * @param normalMatrix the matrix to bind
  43140. */
  43141. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43142. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43143. };
  43144. PushMaterial.prototype.bind = function (world, mesh) {
  43145. if (!mesh) {
  43146. return;
  43147. }
  43148. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43149. };
  43150. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43151. if (effect === void 0) { effect = null; }
  43152. _super.prototype._afterBind.call(this, mesh);
  43153. this.getScene()._cachedEffect = effect;
  43154. };
  43155. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43156. if (visibility === void 0) { visibility = 1; }
  43157. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43158. };
  43159. return PushMaterial;
  43160. }(BABYLON.Material));
  43161. BABYLON.PushMaterial = PushMaterial;
  43162. })(BABYLON || (BABYLON = {}));
  43163. //# sourceMappingURL=babylon.pushMaterial.js.map
  43164. var BABYLON;
  43165. (function (BABYLON) {
  43166. /** @hidden */
  43167. var StandardMaterialDefines = /** @class */ (function (_super) {
  43168. __extends(StandardMaterialDefines, _super);
  43169. function StandardMaterialDefines() {
  43170. var _this = _super.call(this) || this;
  43171. _this.MAINUV1 = false;
  43172. _this.MAINUV2 = false;
  43173. _this.DIFFUSE = false;
  43174. _this.DIFFUSEDIRECTUV = 0;
  43175. _this.AMBIENT = false;
  43176. _this.AMBIENTDIRECTUV = 0;
  43177. _this.OPACITY = false;
  43178. _this.OPACITYDIRECTUV = 0;
  43179. _this.OPACITYRGB = false;
  43180. _this.REFLECTION = false;
  43181. _this.EMISSIVE = false;
  43182. _this.EMISSIVEDIRECTUV = 0;
  43183. _this.SPECULAR = false;
  43184. _this.SPECULARDIRECTUV = 0;
  43185. _this.BUMP = false;
  43186. _this.BUMPDIRECTUV = 0;
  43187. _this.PARALLAX = false;
  43188. _this.PARALLAXOCCLUSION = false;
  43189. _this.SPECULAROVERALPHA = false;
  43190. _this.CLIPPLANE = false;
  43191. _this.ALPHATEST = false;
  43192. _this.DEPTHPREPASS = false;
  43193. _this.ALPHAFROMDIFFUSE = false;
  43194. _this.POINTSIZE = false;
  43195. _this.FOG = false;
  43196. _this.SPECULARTERM = false;
  43197. _this.DIFFUSEFRESNEL = false;
  43198. _this.OPACITYFRESNEL = false;
  43199. _this.REFLECTIONFRESNEL = false;
  43200. _this.REFRACTIONFRESNEL = false;
  43201. _this.EMISSIVEFRESNEL = false;
  43202. _this.FRESNEL = false;
  43203. _this.NORMAL = false;
  43204. _this.UV1 = false;
  43205. _this.UV2 = false;
  43206. _this.VERTEXCOLOR = false;
  43207. _this.VERTEXALPHA = false;
  43208. _this.NUM_BONE_INFLUENCERS = 0;
  43209. _this.BonesPerMesh = 0;
  43210. _this.INSTANCES = false;
  43211. _this.GLOSSINESS = false;
  43212. _this.ROUGHNESS = false;
  43213. _this.EMISSIVEASILLUMINATION = false;
  43214. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43215. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43216. _this.LIGHTMAP = false;
  43217. _this.LIGHTMAPDIRECTUV = 0;
  43218. _this.OBJECTSPACE_NORMALMAP = false;
  43219. _this.USELIGHTMAPASSHADOWMAP = false;
  43220. _this.REFLECTIONMAP_3D = false;
  43221. _this.REFLECTIONMAP_SPHERICAL = false;
  43222. _this.REFLECTIONMAP_PLANAR = false;
  43223. _this.REFLECTIONMAP_CUBIC = false;
  43224. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43225. _this.REFLECTIONMAP_PROJECTION = false;
  43226. _this.REFLECTIONMAP_SKYBOX = false;
  43227. _this.REFLECTIONMAP_EXPLICIT = false;
  43228. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43229. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43230. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43231. _this.INVERTCUBICMAP = false;
  43232. _this.LOGARITHMICDEPTH = false;
  43233. _this.REFRACTION = false;
  43234. _this.REFRACTIONMAP_3D = false;
  43235. _this.REFLECTIONOVERALPHA = false;
  43236. _this.TWOSIDEDLIGHTING = false;
  43237. _this.SHADOWFLOAT = false;
  43238. _this.MORPHTARGETS = false;
  43239. _this.MORPHTARGETS_NORMAL = false;
  43240. _this.MORPHTARGETS_TANGENT = false;
  43241. _this.NUM_MORPH_INFLUENCERS = 0;
  43242. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43243. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43244. _this.IMAGEPROCESSING = false;
  43245. _this.VIGNETTE = false;
  43246. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43247. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43248. _this.TONEMAPPING = false;
  43249. _this.CONTRAST = false;
  43250. _this.COLORCURVES = false;
  43251. _this.COLORGRADING = false;
  43252. _this.COLORGRADING3D = false;
  43253. _this.SAMPLER3DGREENDEPTH = false;
  43254. _this.SAMPLER3DBGRMAP = false;
  43255. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43256. /**
  43257. * If the reflection texture on this material is in linear color space
  43258. * @hidden
  43259. */
  43260. _this.IS_REFLECTION_LINEAR = false;
  43261. /**
  43262. * If the refraction texture on this material is in linear color space
  43263. * @hidden
  43264. */
  43265. _this.IS_REFRACTION_LINEAR = false;
  43266. _this.EXPOSURE = false;
  43267. _this.rebuild();
  43268. return _this;
  43269. }
  43270. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43271. var modes = [
  43272. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43273. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43274. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43275. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43276. ];
  43277. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43278. var mode = modes_1[_i];
  43279. this[mode] = (mode === modeToEnable);
  43280. }
  43281. };
  43282. return StandardMaterialDefines;
  43283. }(BABYLON.MaterialDefines));
  43284. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43285. var StandardMaterial = /** @class */ (function (_super) {
  43286. __extends(StandardMaterial, _super);
  43287. function StandardMaterial(name, scene) {
  43288. var _this = _super.call(this, name, scene) || this;
  43289. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43290. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43291. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43292. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43293. _this.specularPower = 64;
  43294. _this._useAlphaFromDiffuseTexture = false;
  43295. _this._useEmissiveAsIllumination = false;
  43296. _this._linkEmissiveWithDiffuse = false;
  43297. _this._useSpecularOverAlpha = false;
  43298. _this._useReflectionOverAlpha = false;
  43299. _this._disableLighting = false;
  43300. _this._useObjectSpaceNormalMap = false;
  43301. _this._useParallax = false;
  43302. _this._useParallaxOcclusion = false;
  43303. _this.parallaxScaleBias = 0.05;
  43304. _this._roughness = 0;
  43305. _this.indexOfRefraction = 0.98;
  43306. _this.invertRefractionY = true;
  43307. /**
  43308. * Defines the alpha limits in alpha test mode
  43309. */
  43310. _this.alphaCutOff = 0.4;
  43311. _this._useLightmapAsShadowmap = false;
  43312. _this._useReflectionFresnelFromSpecular = false;
  43313. _this._useGlossinessFromSpecularMapAlpha = false;
  43314. _this._maxSimultaneousLights = 4;
  43315. /**
  43316. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43317. */
  43318. _this._invertNormalMapX = false;
  43319. /**
  43320. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43321. */
  43322. _this._invertNormalMapY = false;
  43323. /**
  43324. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43325. */
  43326. _this._twoSidedLighting = false;
  43327. _this._renderTargets = new BABYLON.SmartArray(16);
  43328. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43329. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43330. // Setup the default processing configuration to the scene.
  43331. _this._attachImageProcessingConfiguration(null);
  43332. _this.getRenderTargetTextures = function () {
  43333. _this._renderTargets.reset();
  43334. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43335. _this._renderTargets.push(_this._reflectionTexture);
  43336. }
  43337. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43338. _this._renderTargets.push(_this._refractionTexture);
  43339. }
  43340. return _this._renderTargets;
  43341. };
  43342. return _this;
  43343. }
  43344. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43345. /**
  43346. * Gets the image processing configuration used either in this material.
  43347. */
  43348. get: function () {
  43349. return this._imageProcessingConfiguration;
  43350. },
  43351. /**
  43352. * Sets the Default image processing configuration used either in the this material.
  43353. *
  43354. * If sets to null, the scene one is in use.
  43355. */
  43356. set: function (value) {
  43357. this._attachImageProcessingConfiguration(value);
  43358. // Ensure the effect will be rebuilt.
  43359. this._markAllSubMeshesAsTexturesDirty();
  43360. },
  43361. enumerable: true,
  43362. configurable: true
  43363. });
  43364. /**
  43365. * Attaches a new image processing configuration to the Standard Material.
  43366. * @param configuration
  43367. */
  43368. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43369. var _this = this;
  43370. if (configuration === this._imageProcessingConfiguration) {
  43371. return;
  43372. }
  43373. // Detaches observer.
  43374. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43375. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43376. }
  43377. // Pick the scene configuration if needed.
  43378. if (!configuration) {
  43379. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43380. }
  43381. else {
  43382. this._imageProcessingConfiguration = configuration;
  43383. }
  43384. // Attaches observer.
  43385. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43386. _this._markAllSubMeshesAsImageProcessingDirty();
  43387. });
  43388. };
  43389. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43390. /**
  43391. * Gets wether the color curves effect is enabled.
  43392. */
  43393. get: function () {
  43394. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43395. },
  43396. /**
  43397. * Sets wether the color curves effect is enabled.
  43398. */
  43399. set: function (value) {
  43400. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43401. },
  43402. enumerable: true,
  43403. configurable: true
  43404. });
  43405. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43406. /**
  43407. * Gets wether the color grading effect is enabled.
  43408. */
  43409. get: function () {
  43410. return this.imageProcessingConfiguration.colorGradingEnabled;
  43411. },
  43412. /**
  43413. * Gets wether the color grading effect is enabled.
  43414. */
  43415. set: function (value) {
  43416. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43417. },
  43418. enumerable: true,
  43419. configurable: true
  43420. });
  43421. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43422. /**
  43423. * Gets wether tonemapping is enabled or not.
  43424. */
  43425. get: function () {
  43426. return this._imageProcessingConfiguration.toneMappingEnabled;
  43427. },
  43428. /**
  43429. * Sets wether tonemapping is enabled or not
  43430. */
  43431. set: function (value) {
  43432. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43433. },
  43434. enumerable: true,
  43435. configurable: true
  43436. });
  43437. ;
  43438. ;
  43439. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43440. /**
  43441. * The camera exposure used on this material.
  43442. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43443. * This corresponds to a photographic exposure.
  43444. */
  43445. get: function () {
  43446. return this._imageProcessingConfiguration.exposure;
  43447. },
  43448. /**
  43449. * The camera exposure used on this material.
  43450. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43451. * This corresponds to a photographic exposure.
  43452. */
  43453. set: function (value) {
  43454. this._imageProcessingConfiguration.exposure = value;
  43455. },
  43456. enumerable: true,
  43457. configurable: true
  43458. });
  43459. ;
  43460. ;
  43461. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43462. /**
  43463. * Gets The camera contrast used on this material.
  43464. */
  43465. get: function () {
  43466. return this._imageProcessingConfiguration.contrast;
  43467. },
  43468. /**
  43469. * Sets The camera contrast used on this material.
  43470. */
  43471. set: function (value) {
  43472. this._imageProcessingConfiguration.contrast = value;
  43473. },
  43474. enumerable: true,
  43475. configurable: true
  43476. });
  43477. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43478. /**
  43479. * Gets the Color Grading 2D Lookup Texture.
  43480. */
  43481. get: function () {
  43482. return this._imageProcessingConfiguration.colorGradingTexture;
  43483. },
  43484. /**
  43485. * Sets the Color Grading 2D Lookup Texture.
  43486. */
  43487. set: function (value) {
  43488. this._imageProcessingConfiguration.colorGradingTexture = value;
  43489. },
  43490. enumerable: true,
  43491. configurable: true
  43492. });
  43493. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43494. /**
  43495. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43496. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43497. * 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;
  43498. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43499. */
  43500. get: function () {
  43501. return this._imageProcessingConfiguration.colorCurves;
  43502. },
  43503. /**
  43504. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43505. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43506. * 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;
  43507. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43508. */
  43509. set: function (value) {
  43510. this._imageProcessingConfiguration.colorCurves = value;
  43511. },
  43512. enumerable: true,
  43513. configurable: true
  43514. });
  43515. StandardMaterial.prototype.getClassName = function () {
  43516. return "StandardMaterial";
  43517. };
  43518. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43519. get: function () {
  43520. return this._useLogarithmicDepth;
  43521. },
  43522. set: function (value) {
  43523. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43524. this._markAllSubMeshesAsMiscDirty();
  43525. },
  43526. enumerable: true,
  43527. configurable: true
  43528. });
  43529. StandardMaterial.prototype.needAlphaBlending = function () {
  43530. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43531. };
  43532. StandardMaterial.prototype.needAlphaTesting = function () {
  43533. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43534. };
  43535. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43536. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43537. };
  43538. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43539. return this._diffuseTexture;
  43540. };
  43541. /**
  43542. * Child classes can use it to update shaders
  43543. */
  43544. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43545. if (useInstances === void 0) { useInstances = false; }
  43546. if (subMesh.effect && this.isFrozen) {
  43547. if (this._wasPreviouslyReady && subMesh.effect) {
  43548. return true;
  43549. }
  43550. }
  43551. if (!subMesh._materialDefines) {
  43552. subMesh._materialDefines = new StandardMaterialDefines();
  43553. }
  43554. var scene = this.getScene();
  43555. var defines = subMesh._materialDefines;
  43556. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43557. if (defines._renderId === scene.getRenderId()) {
  43558. return true;
  43559. }
  43560. }
  43561. var engine = scene.getEngine();
  43562. // Lights
  43563. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43564. // Textures
  43565. if (defines._areTexturesDirty) {
  43566. defines._needUVs = false;
  43567. defines.MAINUV1 = false;
  43568. defines.MAINUV2 = false;
  43569. if (scene.texturesEnabled) {
  43570. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43571. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43572. return false;
  43573. }
  43574. else {
  43575. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43576. }
  43577. }
  43578. else {
  43579. defines.DIFFUSE = false;
  43580. }
  43581. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43582. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43583. return false;
  43584. }
  43585. else {
  43586. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43587. }
  43588. }
  43589. else {
  43590. defines.AMBIENT = false;
  43591. }
  43592. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43593. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43594. return false;
  43595. }
  43596. else {
  43597. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43598. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43599. }
  43600. }
  43601. else {
  43602. defines.OPACITY = false;
  43603. }
  43604. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43605. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43606. return false;
  43607. }
  43608. else {
  43609. defines._needNormals = true;
  43610. defines.REFLECTION = true;
  43611. defines.ROUGHNESS = (this._roughness > 0);
  43612. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43613. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43614. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43615. switch (this._reflectionTexture.coordinatesMode) {
  43616. case BABYLON.Texture.EXPLICIT_MODE:
  43617. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43618. break;
  43619. case BABYLON.Texture.PLANAR_MODE:
  43620. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43621. break;
  43622. case BABYLON.Texture.PROJECTION_MODE:
  43623. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43624. break;
  43625. case BABYLON.Texture.SKYBOX_MODE:
  43626. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43627. break;
  43628. case BABYLON.Texture.SPHERICAL_MODE:
  43629. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43630. break;
  43631. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43632. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43633. break;
  43634. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43635. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43636. break;
  43637. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43638. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43639. break;
  43640. case BABYLON.Texture.CUBIC_MODE:
  43641. case BABYLON.Texture.INVCUBIC_MODE:
  43642. default:
  43643. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43644. break;
  43645. }
  43646. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43647. }
  43648. }
  43649. else {
  43650. defines.REFLECTION = false;
  43651. }
  43652. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43653. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43654. return false;
  43655. }
  43656. else {
  43657. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43658. }
  43659. }
  43660. else {
  43661. defines.EMISSIVE = false;
  43662. }
  43663. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43664. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43665. return false;
  43666. }
  43667. else {
  43668. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43669. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43670. }
  43671. }
  43672. else {
  43673. defines.LIGHTMAP = false;
  43674. }
  43675. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43676. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43677. return false;
  43678. }
  43679. else {
  43680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43681. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43682. }
  43683. }
  43684. else {
  43685. defines.SPECULAR = false;
  43686. }
  43687. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43688. // Bump texure can not be not blocking.
  43689. if (!this._bumpTexture.isReady()) {
  43690. return false;
  43691. }
  43692. else {
  43693. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43694. defines.PARALLAX = this._useParallax;
  43695. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43696. }
  43697. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43698. }
  43699. else {
  43700. defines.BUMP = false;
  43701. }
  43702. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43703. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43704. return false;
  43705. }
  43706. else {
  43707. defines._needUVs = true;
  43708. defines.REFRACTION = true;
  43709. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43710. }
  43711. }
  43712. else {
  43713. defines.REFRACTION = false;
  43714. }
  43715. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43716. }
  43717. else {
  43718. defines.DIFFUSE = false;
  43719. defines.AMBIENT = false;
  43720. defines.OPACITY = false;
  43721. defines.REFLECTION = false;
  43722. defines.EMISSIVE = false;
  43723. defines.LIGHTMAP = false;
  43724. defines.BUMP = false;
  43725. defines.REFRACTION = false;
  43726. }
  43727. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43728. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43729. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43730. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43731. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43732. }
  43733. if (defines._areImageProcessingDirty) {
  43734. if (!this._imageProcessingConfiguration.isReady()) {
  43735. return false;
  43736. }
  43737. this._imageProcessingConfiguration.prepareDefines(defines);
  43738. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43739. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43740. }
  43741. if (defines._areFresnelDirty) {
  43742. if (StandardMaterial.FresnelEnabled) {
  43743. // Fresnel
  43744. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43745. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43746. this._reflectionFresnelParameters) {
  43747. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43748. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43749. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43750. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43751. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43752. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43753. defines._needNormals = true;
  43754. defines.FRESNEL = true;
  43755. }
  43756. }
  43757. else {
  43758. defines.FRESNEL = false;
  43759. }
  43760. }
  43761. // Misc.
  43762. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43763. // Attribs
  43764. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43765. // Values that need to be evaluated on every frame
  43766. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43767. // Get correct effect
  43768. if (defines.isDirty) {
  43769. defines.markAsProcessed();
  43770. scene.resetCachedMaterial();
  43771. // Fallbacks
  43772. var fallbacks = new BABYLON.EffectFallbacks();
  43773. if (defines.REFLECTION) {
  43774. fallbacks.addFallback(0, "REFLECTION");
  43775. }
  43776. if (defines.SPECULAR) {
  43777. fallbacks.addFallback(0, "SPECULAR");
  43778. }
  43779. if (defines.BUMP) {
  43780. fallbacks.addFallback(0, "BUMP");
  43781. }
  43782. if (defines.PARALLAX) {
  43783. fallbacks.addFallback(1, "PARALLAX");
  43784. }
  43785. if (defines.PARALLAXOCCLUSION) {
  43786. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43787. }
  43788. if (defines.SPECULAROVERALPHA) {
  43789. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43790. }
  43791. if (defines.FOG) {
  43792. fallbacks.addFallback(1, "FOG");
  43793. }
  43794. if (defines.POINTSIZE) {
  43795. fallbacks.addFallback(0, "POINTSIZE");
  43796. }
  43797. if (defines.LOGARITHMICDEPTH) {
  43798. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43799. }
  43800. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43801. if (defines.SPECULARTERM) {
  43802. fallbacks.addFallback(0, "SPECULARTERM");
  43803. }
  43804. if (defines.DIFFUSEFRESNEL) {
  43805. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43806. }
  43807. if (defines.OPACITYFRESNEL) {
  43808. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43809. }
  43810. if (defines.REFLECTIONFRESNEL) {
  43811. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43812. }
  43813. if (defines.EMISSIVEFRESNEL) {
  43814. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43815. }
  43816. if (defines.FRESNEL) {
  43817. fallbacks.addFallback(4, "FRESNEL");
  43818. }
  43819. //Attributes
  43820. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43821. if (defines.NORMAL) {
  43822. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43823. }
  43824. if (defines.UV1) {
  43825. attribs.push(BABYLON.VertexBuffer.UVKind);
  43826. }
  43827. if (defines.UV2) {
  43828. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43829. }
  43830. if (defines.VERTEXCOLOR) {
  43831. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43832. }
  43833. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43834. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43835. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43836. var shaderName = "default";
  43837. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43838. "vFogInfos", "vFogColor", "pointSize",
  43839. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43840. "mBones",
  43841. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43842. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43843. "vReflectionPosition", "vReflectionSize",
  43844. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43845. ];
  43846. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43847. var uniformBuffers = ["Material", "Scene"];
  43848. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43849. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43850. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43851. uniformsNames: uniforms,
  43852. uniformBuffersNames: uniformBuffers,
  43853. samplers: samplers,
  43854. defines: defines,
  43855. maxSimultaneousLights: this._maxSimultaneousLights
  43856. });
  43857. if (this.customShaderNameResolve) {
  43858. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43859. }
  43860. var join = defines.toString();
  43861. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43862. attributes: attribs,
  43863. uniformsNames: uniforms,
  43864. uniformBuffersNames: uniformBuffers,
  43865. samplers: samplers,
  43866. defines: join,
  43867. fallbacks: fallbacks,
  43868. onCompiled: this.onCompiled,
  43869. onError: this.onError,
  43870. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43871. }, engine), defines);
  43872. this.buildUniformLayout();
  43873. }
  43874. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43875. return false;
  43876. }
  43877. defines._renderId = scene.getRenderId();
  43878. this._wasPreviouslyReady = true;
  43879. return true;
  43880. };
  43881. StandardMaterial.prototype.buildUniformLayout = function () {
  43882. // Order is important !
  43883. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43884. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43885. this._uniformBuffer.addUniform("opacityParts", 4);
  43886. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43887. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43888. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43889. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43890. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43891. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43892. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43893. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43894. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43895. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43896. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43897. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43898. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43899. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43900. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43901. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43902. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43903. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43904. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43905. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43906. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43907. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43908. this._uniformBuffer.addUniform("specularMatrix", 16);
  43909. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43910. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43911. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43912. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43913. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43914. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43915. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43916. this._uniformBuffer.addUniform("pointSize", 1);
  43917. this._uniformBuffer.create();
  43918. };
  43919. StandardMaterial.prototype.unbind = function () {
  43920. if (this._activeEffect) {
  43921. var needFlag = false;
  43922. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43923. this._activeEffect.setTexture("reflection2DSampler", null);
  43924. needFlag = true;
  43925. }
  43926. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43927. this._activeEffect.setTexture("refraction2DSampler", null);
  43928. needFlag = true;
  43929. }
  43930. if (needFlag) {
  43931. this._markAllSubMeshesAsTexturesDirty();
  43932. }
  43933. }
  43934. _super.prototype.unbind.call(this);
  43935. };
  43936. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43937. var scene = this.getScene();
  43938. var defines = subMesh._materialDefines;
  43939. if (!defines) {
  43940. return;
  43941. }
  43942. var effect = subMesh.effect;
  43943. if (!effect) {
  43944. return;
  43945. }
  43946. this._activeEffect = effect;
  43947. // Matrices
  43948. this.bindOnlyWorldMatrix(world);
  43949. // Normal Matrix
  43950. if (defines.OBJECTSPACE_NORMALMAP) {
  43951. world.toNormalMatrix(this._normalMatrix);
  43952. this.bindOnlyNormalMatrix(this._normalMatrix);
  43953. }
  43954. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43955. // Bones
  43956. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43957. if (mustRebind) {
  43958. this._uniformBuffer.bindToEffect(effect, "Material");
  43959. this.bindViewProjection(effect);
  43960. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43961. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43962. // Fresnel
  43963. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43964. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43965. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43966. }
  43967. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43968. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43969. }
  43970. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43971. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43972. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43973. }
  43974. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43975. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43976. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43977. }
  43978. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43979. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43980. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43981. }
  43982. }
  43983. // Textures
  43984. if (scene.texturesEnabled) {
  43985. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43986. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43987. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43988. if (this._diffuseTexture.hasAlpha) {
  43989. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43990. }
  43991. }
  43992. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43993. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43994. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43995. }
  43996. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43997. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43998. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43999. }
  44000. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44001. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44002. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44003. if (this._reflectionTexture.boundingBoxSize) {
  44004. var cubeTexture = this._reflectionTexture;
  44005. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44006. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44007. }
  44008. }
  44009. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44010. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44011. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44012. }
  44013. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44014. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44015. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44016. }
  44017. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44018. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44019. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44020. }
  44021. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44022. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44023. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44024. if (scene._mirroredCameraPosition) {
  44025. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44026. }
  44027. else {
  44028. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44029. }
  44030. }
  44031. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44032. var depth = 1.0;
  44033. if (!this._refractionTexture.isCube) {
  44034. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44035. if (this._refractionTexture.depth) {
  44036. depth = this._refractionTexture.depth;
  44037. }
  44038. }
  44039. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44040. }
  44041. }
  44042. // Point size
  44043. if (this.pointsCloud) {
  44044. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44045. }
  44046. if (defines.SPECULARTERM) {
  44047. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44048. }
  44049. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44050. // Diffuse
  44051. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44052. }
  44053. // Textures
  44054. if (scene.texturesEnabled) {
  44055. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44056. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44057. }
  44058. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44059. effect.setTexture("ambientSampler", this._ambientTexture);
  44060. }
  44061. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44062. effect.setTexture("opacitySampler", this._opacityTexture);
  44063. }
  44064. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44065. if (this._reflectionTexture.isCube) {
  44066. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44067. }
  44068. else {
  44069. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44070. }
  44071. }
  44072. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44073. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44074. }
  44075. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44076. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44077. }
  44078. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44079. effect.setTexture("specularSampler", this._specularTexture);
  44080. }
  44081. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44082. effect.setTexture("bumpSampler", this._bumpTexture);
  44083. }
  44084. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44085. var depth = 1.0;
  44086. if (this._refractionTexture.isCube) {
  44087. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44088. }
  44089. else {
  44090. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44091. }
  44092. }
  44093. }
  44094. // Clip plane
  44095. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44096. // Colors
  44097. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44098. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44099. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44100. }
  44101. if (mustRebind || !this.isFrozen) {
  44102. // Lights
  44103. if (scene.lightsEnabled && !this._disableLighting) {
  44104. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44105. }
  44106. // View
  44107. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44108. this.bindView(effect);
  44109. }
  44110. // Fog
  44111. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44112. // Morph targets
  44113. if (defines.NUM_MORPH_INFLUENCERS) {
  44114. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44115. }
  44116. // Log. depth
  44117. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44118. // image processing
  44119. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44120. this._imageProcessingConfiguration.bind(this._activeEffect);
  44121. }
  44122. }
  44123. this._uniformBuffer.update();
  44124. this._afterBind(mesh, this._activeEffect);
  44125. };
  44126. StandardMaterial.prototype.getAnimatables = function () {
  44127. var results = [];
  44128. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44129. results.push(this._diffuseTexture);
  44130. }
  44131. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44132. results.push(this._ambientTexture);
  44133. }
  44134. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44135. results.push(this._opacityTexture);
  44136. }
  44137. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44138. results.push(this._reflectionTexture);
  44139. }
  44140. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44141. results.push(this._emissiveTexture);
  44142. }
  44143. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44144. results.push(this._specularTexture);
  44145. }
  44146. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44147. results.push(this._bumpTexture);
  44148. }
  44149. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44150. results.push(this._lightmapTexture);
  44151. }
  44152. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44153. results.push(this._refractionTexture);
  44154. }
  44155. return results;
  44156. };
  44157. StandardMaterial.prototype.getActiveTextures = function () {
  44158. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44159. if (this._diffuseTexture) {
  44160. activeTextures.push(this._diffuseTexture);
  44161. }
  44162. if (this._ambientTexture) {
  44163. activeTextures.push(this._ambientTexture);
  44164. }
  44165. if (this._opacityTexture) {
  44166. activeTextures.push(this._opacityTexture);
  44167. }
  44168. if (this._reflectionTexture) {
  44169. activeTextures.push(this._reflectionTexture);
  44170. }
  44171. if (this._emissiveTexture) {
  44172. activeTextures.push(this._emissiveTexture);
  44173. }
  44174. if (this._specularTexture) {
  44175. activeTextures.push(this._specularTexture);
  44176. }
  44177. if (this._bumpTexture) {
  44178. activeTextures.push(this._bumpTexture);
  44179. }
  44180. if (this._lightmapTexture) {
  44181. activeTextures.push(this._lightmapTexture);
  44182. }
  44183. if (this._refractionTexture) {
  44184. activeTextures.push(this._refractionTexture);
  44185. }
  44186. return activeTextures;
  44187. };
  44188. StandardMaterial.prototype.hasTexture = function (texture) {
  44189. if (_super.prototype.hasTexture.call(this, texture)) {
  44190. return true;
  44191. }
  44192. if (this._diffuseTexture === texture) {
  44193. return true;
  44194. }
  44195. if (this._ambientTexture === texture) {
  44196. return true;
  44197. }
  44198. if (this._opacityTexture === texture) {
  44199. return true;
  44200. }
  44201. if (this._reflectionTexture === texture) {
  44202. return true;
  44203. }
  44204. if (this._emissiveTexture === texture) {
  44205. return true;
  44206. }
  44207. if (this._specularTexture === texture) {
  44208. return true;
  44209. }
  44210. if (this._bumpTexture === texture) {
  44211. return true;
  44212. }
  44213. if (this._lightmapTexture === texture) {
  44214. return true;
  44215. }
  44216. if (this._refractionTexture === texture) {
  44217. return true;
  44218. }
  44219. return false;
  44220. };
  44221. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44222. if (forceDisposeTextures) {
  44223. if (this._diffuseTexture) {
  44224. this._diffuseTexture.dispose();
  44225. }
  44226. if (this._ambientTexture) {
  44227. this._ambientTexture.dispose();
  44228. }
  44229. if (this._opacityTexture) {
  44230. this._opacityTexture.dispose();
  44231. }
  44232. if (this._reflectionTexture) {
  44233. this._reflectionTexture.dispose();
  44234. }
  44235. if (this._emissiveTexture) {
  44236. this._emissiveTexture.dispose();
  44237. }
  44238. if (this._specularTexture) {
  44239. this._specularTexture.dispose();
  44240. }
  44241. if (this._bumpTexture) {
  44242. this._bumpTexture.dispose();
  44243. }
  44244. if (this._lightmapTexture) {
  44245. this._lightmapTexture.dispose();
  44246. }
  44247. if (this._refractionTexture) {
  44248. this._refractionTexture.dispose();
  44249. }
  44250. }
  44251. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44252. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44253. }
  44254. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44255. };
  44256. StandardMaterial.prototype.clone = function (name) {
  44257. var _this = this;
  44258. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44259. result.name = name;
  44260. result.id = name;
  44261. return result;
  44262. };
  44263. StandardMaterial.prototype.serialize = function () {
  44264. return BABYLON.SerializationHelper.Serialize(this);
  44265. };
  44266. // Statics
  44267. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44268. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44269. };
  44270. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44271. get: function () {
  44272. return StandardMaterial._DiffuseTextureEnabled;
  44273. },
  44274. set: function (value) {
  44275. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44276. return;
  44277. }
  44278. StandardMaterial._DiffuseTextureEnabled = value;
  44279. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44280. },
  44281. enumerable: true,
  44282. configurable: true
  44283. });
  44284. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44285. get: function () {
  44286. return StandardMaterial._AmbientTextureEnabled;
  44287. },
  44288. set: function (value) {
  44289. if (StandardMaterial._AmbientTextureEnabled === value) {
  44290. return;
  44291. }
  44292. StandardMaterial._AmbientTextureEnabled = value;
  44293. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44294. },
  44295. enumerable: true,
  44296. configurable: true
  44297. });
  44298. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44299. get: function () {
  44300. return StandardMaterial._OpacityTextureEnabled;
  44301. },
  44302. set: function (value) {
  44303. if (StandardMaterial._OpacityTextureEnabled === value) {
  44304. return;
  44305. }
  44306. StandardMaterial._OpacityTextureEnabled = value;
  44307. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44308. },
  44309. enumerable: true,
  44310. configurable: true
  44311. });
  44312. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44313. get: function () {
  44314. return StandardMaterial._ReflectionTextureEnabled;
  44315. },
  44316. set: function (value) {
  44317. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44318. return;
  44319. }
  44320. StandardMaterial._ReflectionTextureEnabled = value;
  44321. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44322. },
  44323. enumerable: true,
  44324. configurable: true
  44325. });
  44326. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44327. get: function () {
  44328. return StandardMaterial._EmissiveTextureEnabled;
  44329. },
  44330. set: function (value) {
  44331. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44332. return;
  44333. }
  44334. StandardMaterial._EmissiveTextureEnabled = value;
  44335. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44336. },
  44337. enumerable: true,
  44338. configurable: true
  44339. });
  44340. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44341. get: function () {
  44342. return StandardMaterial._SpecularTextureEnabled;
  44343. },
  44344. set: function (value) {
  44345. if (StandardMaterial._SpecularTextureEnabled === value) {
  44346. return;
  44347. }
  44348. StandardMaterial._SpecularTextureEnabled = value;
  44349. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44350. },
  44351. enumerable: true,
  44352. configurable: true
  44353. });
  44354. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44355. get: function () {
  44356. return StandardMaterial._BumpTextureEnabled;
  44357. },
  44358. set: function (value) {
  44359. if (StandardMaterial._BumpTextureEnabled === value) {
  44360. return;
  44361. }
  44362. StandardMaterial._BumpTextureEnabled = value;
  44363. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44364. },
  44365. enumerable: true,
  44366. configurable: true
  44367. });
  44368. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44369. get: function () {
  44370. return StandardMaterial._LightmapTextureEnabled;
  44371. },
  44372. set: function (value) {
  44373. if (StandardMaterial._LightmapTextureEnabled === value) {
  44374. return;
  44375. }
  44376. StandardMaterial._LightmapTextureEnabled = value;
  44377. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44378. },
  44379. enumerable: true,
  44380. configurable: true
  44381. });
  44382. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44383. get: function () {
  44384. return StandardMaterial._RefractionTextureEnabled;
  44385. },
  44386. set: function (value) {
  44387. if (StandardMaterial._RefractionTextureEnabled === value) {
  44388. return;
  44389. }
  44390. StandardMaterial._RefractionTextureEnabled = value;
  44391. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44392. },
  44393. enumerable: true,
  44394. configurable: true
  44395. });
  44396. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44397. get: function () {
  44398. return StandardMaterial._ColorGradingTextureEnabled;
  44399. },
  44400. set: function (value) {
  44401. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44402. return;
  44403. }
  44404. StandardMaterial._ColorGradingTextureEnabled = value;
  44405. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44406. },
  44407. enumerable: true,
  44408. configurable: true
  44409. });
  44410. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44411. get: function () {
  44412. return StandardMaterial._FresnelEnabled;
  44413. },
  44414. set: function (value) {
  44415. if (StandardMaterial._FresnelEnabled === value) {
  44416. return;
  44417. }
  44418. StandardMaterial._FresnelEnabled = value;
  44419. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44420. },
  44421. enumerable: true,
  44422. configurable: true
  44423. });
  44424. // Flags used to enable or disable a type of texture for all Standard Materials
  44425. StandardMaterial._DiffuseTextureEnabled = true;
  44426. StandardMaterial._AmbientTextureEnabled = true;
  44427. StandardMaterial._OpacityTextureEnabled = true;
  44428. StandardMaterial._ReflectionTextureEnabled = true;
  44429. StandardMaterial._EmissiveTextureEnabled = true;
  44430. StandardMaterial._SpecularTextureEnabled = true;
  44431. StandardMaterial._BumpTextureEnabled = true;
  44432. StandardMaterial._LightmapTextureEnabled = true;
  44433. StandardMaterial._RefractionTextureEnabled = true;
  44434. StandardMaterial._ColorGradingTextureEnabled = true;
  44435. StandardMaterial._FresnelEnabled = true;
  44436. __decorate([
  44437. BABYLON.serializeAsTexture("diffuseTexture")
  44438. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44439. __decorate([
  44440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44441. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44442. __decorate([
  44443. BABYLON.serializeAsTexture("ambientTexture")
  44444. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44445. __decorate([
  44446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44447. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44448. __decorate([
  44449. BABYLON.serializeAsTexture("opacityTexture")
  44450. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44451. __decorate([
  44452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44453. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44454. __decorate([
  44455. BABYLON.serializeAsTexture("reflectionTexture")
  44456. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44457. __decorate([
  44458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44459. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44460. __decorate([
  44461. BABYLON.serializeAsTexture("emissiveTexture")
  44462. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44463. __decorate([
  44464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44465. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44466. __decorate([
  44467. BABYLON.serializeAsTexture("specularTexture")
  44468. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44469. __decorate([
  44470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44471. ], StandardMaterial.prototype, "specularTexture", void 0);
  44472. __decorate([
  44473. BABYLON.serializeAsTexture("bumpTexture")
  44474. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44475. __decorate([
  44476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44477. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44478. __decorate([
  44479. BABYLON.serializeAsTexture("lightmapTexture")
  44480. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44481. __decorate([
  44482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44483. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44484. __decorate([
  44485. BABYLON.serializeAsTexture("refractionTexture")
  44486. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44487. __decorate([
  44488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44489. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44490. __decorate([
  44491. BABYLON.serializeAsColor3("ambient")
  44492. ], StandardMaterial.prototype, "ambientColor", void 0);
  44493. __decorate([
  44494. BABYLON.serializeAsColor3("diffuse")
  44495. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44496. __decorate([
  44497. BABYLON.serializeAsColor3("specular")
  44498. ], StandardMaterial.prototype, "specularColor", void 0);
  44499. __decorate([
  44500. BABYLON.serializeAsColor3("emissive")
  44501. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44502. __decorate([
  44503. BABYLON.serialize()
  44504. ], StandardMaterial.prototype, "specularPower", void 0);
  44505. __decorate([
  44506. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44507. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44508. __decorate([
  44509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44510. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44511. __decorate([
  44512. BABYLON.serialize("useEmissiveAsIllumination")
  44513. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44514. __decorate([
  44515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44516. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44517. __decorate([
  44518. BABYLON.serialize("linkEmissiveWithDiffuse")
  44519. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44520. __decorate([
  44521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44522. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44523. __decorate([
  44524. BABYLON.serialize("useSpecularOverAlpha")
  44525. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44526. __decorate([
  44527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44528. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44529. __decorate([
  44530. BABYLON.serialize("useReflectionOverAlpha")
  44531. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44532. __decorate([
  44533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44534. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44535. __decorate([
  44536. BABYLON.serialize("disableLighting")
  44537. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44538. __decorate([
  44539. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44540. ], StandardMaterial.prototype, "disableLighting", void 0);
  44541. __decorate([
  44542. BABYLON.serialize("useObjectSpaceNormalMap")
  44543. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44544. __decorate([
  44545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44546. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44547. __decorate([
  44548. BABYLON.serialize("useParallax")
  44549. ], StandardMaterial.prototype, "_useParallax", void 0);
  44550. __decorate([
  44551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44552. ], StandardMaterial.prototype, "useParallax", void 0);
  44553. __decorate([
  44554. BABYLON.serialize("useParallaxOcclusion")
  44555. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44556. __decorate([
  44557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44558. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44559. __decorate([
  44560. BABYLON.serialize()
  44561. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44562. __decorate([
  44563. BABYLON.serialize("roughness")
  44564. ], StandardMaterial.prototype, "_roughness", void 0);
  44565. __decorate([
  44566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44567. ], StandardMaterial.prototype, "roughness", void 0);
  44568. __decorate([
  44569. BABYLON.serialize()
  44570. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44571. __decorate([
  44572. BABYLON.serialize()
  44573. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44574. __decorate([
  44575. BABYLON.serialize()
  44576. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44577. __decorate([
  44578. BABYLON.serialize("useLightmapAsShadowmap")
  44579. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44580. __decorate([
  44581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44582. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44583. __decorate([
  44584. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44585. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44586. __decorate([
  44587. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44588. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44589. __decorate([
  44590. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44591. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44592. __decorate([
  44593. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44594. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44595. __decorate([
  44596. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44597. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44598. __decorate([
  44599. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44600. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44601. __decorate([
  44602. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44603. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44604. __decorate([
  44605. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44606. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44607. __decorate([
  44608. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44609. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44610. __decorate([
  44611. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44612. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44613. __decorate([
  44614. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44615. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44616. __decorate([
  44617. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44618. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44619. __decorate([
  44620. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44621. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44622. __decorate([
  44623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44624. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44625. __decorate([
  44626. BABYLON.serialize("maxSimultaneousLights")
  44627. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44628. __decorate([
  44629. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44630. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44631. __decorate([
  44632. BABYLON.serialize("invertNormalMapX")
  44633. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44634. __decorate([
  44635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44636. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44637. __decorate([
  44638. BABYLON.serialize("invertNormalMapY")
  44639. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44640. __decorate([
  44641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44642. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44643. __decorate([
  44644. BABYLON.serialize("twoSidedLighting")
  44645. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44646. __decorate([
  44647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44648. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44649. __decorate([
  44650. BABYLON.serialize()
  44651. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44652. return StandardMaterial;
  44653. }(BABYLON.PushMaterial));
  44654. BABYLON.StandardMaterial = StandardMaterial;
  44655. })(BABYLON || (BABYLON = {}));
  44656. //# sourceMappingURL=babylon.standardMaterial.js.map
  44657. var BABYLON;
  44658. (function (BABYLON) {
  44659. /**
  44660. * Manages the defines for the PBR Material.
  44661. * @hiddenChildren
  44662. */
  44663. var PBRMaterialDefines = /** @class */ (function (_super) {
  44664. __extends(PBRMaterialDefines, _super);
  44665. /**
  44666. * Initializes the PBR Material defines.
  44667. */
  44668. function PBRMaterialDefines() {
  44669. var _this = _super.call(this) || this;
  44670. _this.PBR = true;
  44671. _this.MAINUV1 = false;
  44672. _this.MAINUV2 = false;
  44673. _this.UV1 = false;
  44674. _this.UV2 = false;
  44675. _this.ALBEDO = false;
  44676. _this.ALBEDODIRECTUV = 0;
  44677. _this.VERTEXCOLOR = false;
  44678. _this.AMBIENT = false;
  44679. _this.AMBIENTDIRECTUV = 0;
  44680. _this.AMBIENTINGRAYSCALE = false;
  44681. _this.OPACITY = false;
  44682. _this.VERTEXALPHA = false;
  44683. _this.OPACITYDIRECTUV = 0;
  44684. _this.OPACITYRGB = false;
  44685. _this.ALPHATEST = false;
  44686. _this.DEPTHPREPASS = false;
  44687. _this.ALPHABLEND = false;
  44688. _this.ALPHAFROMALBEDO = false;
  44689. _this.ALPHATESTVALUE = "0.5";
  44690. _this.SPECULAROVERALPHA = false;
  44691. _this.RADIANCEOVERALPHA = false;
  44692. _this.ALPHAFRESNEL = false;
  44693. _this.LINEARALPHAFRESNEL = false;
  44694. _this.PREMULTIPLYALPHA = false;
  44695. _this.EMISSIVE = false;
  44696. _this.EMISSIVEDIRECTUV = 0;
  44697. _this.REFLECTIVITY = false;
  44698. _this.REFLECTIVITYDIRECTUV = 0;
  44699. _this.SPECULARTERM = false;
  44700. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44701. _this.MICROSURFACEAUTOMATIC = false;
  44702. _this.LODBASEDMICROSFURACE = false;
  44703. _this.MICROSURFACEMAP = false;
  44704. _this.MICROSURFACEMAPDIRECTUV = 0;
  44705. _this.METALLICWORKFLOW = false;
  44706. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44707. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44708. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44709. _this.AOSTOREINMETALMAPRED = false;
  44710. _this.ENVIRONMENTBRDF = false;
  44711. _this.NORMAL = false;
  44712. _this.TANGENT = false;
  44713. _this.BUMP = false;
  44714. _this.BUMPDIRECTUV = 0;
  44715. _this.OBJECTSPACE_NORMALMAP = false;
  44716. _this.PARALLAX = false;
  44717. _this.PARALLAXOCCLUSION = false;
  44718. _this.NORMALXYSCALE = true;
  44719. _this.LIGHTMAP = false;
  44720. _this.LIGHTMAPDIRECTUV = 0;
  44721. _this.USELIGHTMAPASSHADOWMAP = false;
  44722. _this.GAMMALIGHTMAP = false;
  44723. _this.REFLECTION = false;
  44724. _this.REFLECTIONMAP_3D = false;
  44725. _this.REFLECTIONMAP_SPHERICAL = false;
  44726. _this.REFLECTIONMAP_PLANAR = false;
  44727. _this.REFLECTIONMAP_CUBIC = false;
  44728. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44729. _this.REFLECTIONMAP_PROJECTION = false;
  44730. _this.REFLECTIONMAP_SKYBOX = false;
  44731. _this.REFLECTIONMAP_EXPLICIT = false;
  44732. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44733. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44734. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44735. _this.INVERTCUBICMAP = false;
  44736. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44737. _this.USESPHERICALINVERTEX = false;
  44738. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44739. _this.LODINREFLECTIONALPHA = false;
  44740. _this.GAMMAREFLECTION = false;
  44741. _this.RGBDREFLECTION = false;
  44742. _this.RADIANCEOCCLUSION = false;
  44743. _this.HORIZONOCCLUSION = false;
  44744. _this.REFRACTION = false;
  44745. _this.REFRACTIONMAP_3D = false;
  44746. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44747. _this.LODINREFRACTIONALPHA = false;
  44748. _this.GAMMAREFRACTION = false;
  44749. _this.RGBDREFRACTION = false;
  44750. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44751. _this.INSTANCES = false;
  44752. _this.NUM_BONE_INFLUENCERS = 0;
  44753. _this.BonesPerMesh = 0;
  44754. _this.NONUNIFORMSCALING = false;
  44755. _this.MORPHTARGETS = false;
  44756. _this.MORPHTARGETS_NORMAL = false;
  44757. _this.MORPHTARGETS_TANGENT = false;
  44758. _this.NUM_MORPH_INFLUENCERS = 0;
  44759. _this.IMAGEPROCESSING = false;
  44760. _this.VIGNETTE = false;
  44761. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44762. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44763. _this.TONEMAPPING = false;
  44764. _this.CONTRAST = false;
  44765. _this.COLORCURVES = false;
  44766. _this.COLORGRADING = false;
  44767. _this.COLORGRADING3D = false;
  44768. _this.SAMPLER3DGREENDEPTH = false;
  44769. _this.SAMPLER3DBGRMAP = false;
  44770. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44771. _this.EXPOSURE = false;
  44772. _this.USEPHYSICALLIGHTFALLOFF = false;
  44773. _this.TWOSIDEDLIGHTING = false;
  44774. _this.SHADOWFLOAT = false;
  44775. _this.CLIPPLANE = false;
  44776. _this.POINTSIZE = false;
  44777. _this.FOG = false;
  44778. _this.LOGARITHMICDEPTH = false;
  44779. _this.FORCENORMALFORWARD = false;
  44780. _this.SPECULARAA = false;
  44781. _this.UNLIT = false;
  44782. _this.rebuild();
  44783. return _this;
  44784. }
  44785. /**
  44786. * Resets the PBR Material defines.
  44787. */
  44788. PBRMaterialDefines.prototype.reset = function () {
  44789. _super.prototype.reset.call(this);
  44790. this.ALPHATESTVALUE = "0.5";
  44791. this.PBR = true;
  44792. };
  44793. return PBRMaterialDefines;
  44794. }(BABYLON.MaterialDefines));
  44795. /**
  44796. * The Physically based material base class of BJS.
  44797. *
  44798. * This offers the main features of a standard PBR material.
  44799. * For more information, please refer to the documentation :
  44800. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44801. */
  44802. var PBRBaseMaterial = /** @class */ (function (_super) {
  44803. __extends(PBRBaseMaterial, _super);
  44804. /**
  44805. * Instantiates a new PBRMaterial instance.
  44806. *
  44807. * @param name The material name
  44808. * @param scene The scene the material will be use in.
  44809. */
  44810. function PBRBaseMaterial(name, scene) {
  44811. var _this = _super.call(this, name, scene) || this;
  44812. /**
  44813. * Intensity of the direct lights e.g. the four lights available in your scene.
  44814. * This impacts both the direct diffuse and specular highlights.
  44815. */
  44816. _this._directIntensity = 1.0;
  44817. /**
  44818. * Intensity of the emissive part of the material.
  44819. * This helps controlling the emissive effect without modifying the emissive color.
  44820. */
  44821. _this._emissiveIntensity = 1.0;
  44822. /**
  44823. * Intensity of the environment e.g. how much the environment will light the object
  44824. * either through harmonics for rough material or through the refelction for shiny ones.
  44825. */
  44826. _this._environmentIntensity = 1.0;
  44827. /**
  44828. * This is a special control allowing the reduction of the specular highlights coming from the
  44829. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44830. */
  44831. _this._specularIntensity = 1.0;
  44832. /**
  44833. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44834. */
  44835. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44836. /**
  44837. * Debug Control allowing disabling the bump map on this material.
  44838. */
  44839. _this._disableBumpMap = false;
  44840. /**
  44841. * AKA Occlusion Texture Intensity in other nomenclature.
  44842. */
  44843. _this._ambientTextureStrength = 1.0;
  44844. /**
  44845. * The color of a material in ambient lighting.
  44846. */
  44847. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44848. /**
  44849. * AKA Diffuse Color in other nomenclature.
  44850. */
  44851. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44852. /**
  44853. * AKA Specular Color in other nomenclature.
  44854. */
  44855. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44856. /**
  44857. * The color applied when light is reflected from a material.
  44858. */
  44859. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44860. /**
  44861. * The color applied when light is emitted from a material.
  44862. */
  44863. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44864. /**
  44865. * AKA Glossiness in other nomenclature.
  44866. */
  44867. _this._microSurface = 0.9;
  44868. /**
  44869. * source material index of refraction (IOR)' / 'destination material IOR.
  44870. */
  44871. _this._indexOfRefraction = 0.66;
  44872. /**
  44873. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44874. */
  44875. _this._invertRefractionY = false;
  44876. /**
  44877. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44878. * Materials half opaque for instance using refraction could benefit from this control.
  44879. */
  44880. _this._linkRefractionWithTransparency = false;
  44881. /**
  44882. * Specifies that the material will use the light map as a show map.
  44883. */
  44884. _this._useLightmapAsShadowmap = false;
  44885. /**
  44886. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44887. * makes the reflect vector face the model (under horizon).
  44888. */
  44889. _this._useHorizonOcclusion = true;
  44890. /**
  44891. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44892. * too much the area relying on ambient texture to define their ambient occlusion.
  44893. */
  44894. _this._useRadianceOcclusion = true;
  44895. /**
  44896. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44897. */
  44898. _this._useAlphaFromAlbedoTexture = false;
  44899. /**
  44900. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44901. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44902. */
  44903. _this._useSpecularOverAlpha = true;
  44904. /**
  44905. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44906. */
  44907. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44908. /**
  44909. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44910. */
  44911. _this._useRoughnessFromMetallicTextureAlpha = true;
  44912. /**
  44913. * Specifies if the metallic texture contains the roughness information in its green channel.
  44914. */
  44915. _this._useRoughnessFromMetallicTextureGreen = false;
  44916. /**
  44917. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44918. */
  44919. _this._useMetallnessFromMetallicTextureBlue = false;
  44920. /**
  44921. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44922. */
  44923. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44924. /**
  44925. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44926. */
  44927. _this._useAmbientInGrayScale = false;
  44928. /**
  44929. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44930. * The material will try to infer what glossiness each pixel should be.
  44931. */
  44932. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44933. /**
  44934. * BJS is using an harcoded light falloff based on a manually sets up range.
  44935. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44936. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44937. */
  44938. _this._usePhysicalLightFalloff = true;
  44939. /**
  44940. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44941. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44942. */
  44943. _this._useRadianceOverAlpha = true;
  44944. /**
  44945. * Allows using an object space normal map (instead of tangent space).
  44946. */
  44947. _this._useObjectSpaceNormalMap = false;
  44948. /**
  44949. * Allows using the bump map in parallax mode.
  44950. */
  44951. _this._useParallax = false;
  44952. /**
  44953. * Allows using the bump map in parallax occlusion mode.
  44954. */
  44955. _this._useParallaxOcclusion = false;
  44956. /**
  44957. * Controls the scale bias of the parallax mode.
  44958. */
  44959. _this._parallaxScaleBias = 0.05;
  44960. /**
  44961. * If sets to true, disables all the lights affecting the material.
  44962. */
  44963. _this._disableLighting = false;
  44964. /**
  44965. * Number of Simultaneous lights allowed on the material.
  44966. */
  44967. _this._maxSimultaneousLights = 4;
  44968. /**
  44969. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44970. */
  44971. _this._invertNormalMapX = false;
  44972. /**
  44973. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44974. */
  44975. _this._invertNormalMapY = false;
  44976. /**
  44977. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44978. */
  44979. _this._twoSidedLighting = false;
  44980. /**
  44981. * Defines the alpha limits in alpha test mode.
  44982. */
  44983. _this._alphaCutOff = 0.4;
  44984. /**
  44985. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44986. */
  44987. _this._forceAlphaTest = false;
  44988. /**
  44989. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44990. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44991. */
  44992. _this._useAlphaFresnel = false;
  44993. /**
  44994. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44995. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44996. */
  44997. _this._useLinearAlphaFresnel = false;
  44998. /**
  44999. * The transparency mode of the material.
  45000. */
  45001. _this._transparencyMode = null;
  45002. /**
  45003. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45004. * from cos thetav and roughness:
  45005. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45006. */
  45007. _this._environmentBRDFTexture = null;
  45008. /**
  45009. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45010. */
  45011. _this._forceIrradianceInFragment = false;
  45012. /**
  45013. * Force normal to face away from face.
  45014. */
  45015. _this._forceNormalForward = false;
  45016. /**
  45017. * Enables specular anti aliasing in the PBR shader.
  45018. * It will both interacts on the Geometry for analytical and IBL lighting.
  45019. * It also prefilter the roughness map based on the bump values.
  45020. */
  45021. _this._enableSpecularAntiAliasing = false;
  45022. /**
  45023. * Stores the available render targets.
  45024. */
  45025. _this._renderTargets = new BABYLON.SmartArray(16);
  45026. /**
  45027. * Sets the global ambient color for the material used in lighting calculations.
  45028. */
  45029. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45030. /**
  45031. * If set to true, no lighting calculations will be applied.
  45032. */
  45033. _this._unlit = false;
  45034. // Setup the default processing configuration to the scene.
  45035. _this._attachImageProcessingConfiguration(null);
  45036. _this.getRenderTargetTextures = function () {
  45037. _this._renderTargets.reset();
  45038. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45039. _this._renderTargets.push(_this._reflectionTexture);
  45040. }
  45041. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45042. _this._renderTargets.push(_this._refractionTexture);
  45043. }
  45044. return _this._renderTargets;
  45045. };
  45046. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45047. return _this;
  45048. }
  45049. /**
  45050. * Attaches a new image processing configuration to the PBR Material.
  45051. * @param configuration
  45052. */
  45053. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45054. var _this = this;
  45055. if (configuration === this._imageProcessingConfiguration) {
  45056. return;
  45057. }
  45058. // Detaches observer.
  45059. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45060. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45061. }
  45062. // Pick the scene configuration if needed.
  45063. if (!configuration) {
  45064. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45065. }
  45066. else {
  45067. this._imageProcessingConfiguration = configuration;
  45068. }
  45069. // Attaches observer.
  45070. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45071. _this._markAllSubMeshesAsImageProcessingDirty();
  45072. });
  45073. };
  45074. /**
  45075. * Gets the name of the material class.
  45076. */
  45077. PBRBaseMaterial.prototype.getClassName = function () {
  45078. return "PBRBaseMaterial";
  45079. };
  45080. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45081. /**
  45082. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45083. */
  45084. get: function () {
  45085. return this._useLogarithmicDepth;
  45086. },
  45087. /**
  45088. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45089. */
  45090. set: function (value) {
  45091. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45092. },
  45093. enumerable: true,
  45094. configurable: true
  45095. });
  45096. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45097. /**
  45098. * Gets the current transparency mode.
  45099. */
  45100. get: function () {
  45101. return this._transparencyMode;
  45102. },
  45103. /**
  45104. * Sets the transparency mode of the material.
  45105. *
  45106. * | Value | Type | Description |
  45107. * | ----- | ----------------------------------- | ----------- |
  45108. * | 0 | OPAQUE | |
  45109. * | 1 | ALPHATEST | |
  45110. * | 2 | ALPHABLEND | |
  45111. * | 3 | ALPHATESTANDBLEND | |
  45112. *
  45113. */
  45114. set: function (value) {
  45115. if (this._transparencyMode === value) {
  45116. return;
  45117. }
  45118. this._transparencyMode = value;
  45119. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45120. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45121. },
  45122. enumerable: true,
  45123. configurable: true
  45124. });
  45125. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45126. /**
  45127. * Returns true if alpha blending should be disabled.
  45128. */
  45129. get: function () {
  45130. return (this._linkRefractionWithTransparency ||
  45131. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45132. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. /**
  45138. * Specifies whether or not this material should be rendered in alpha blend mode.
  45139. */
  45140. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45141. if (this._disableAlphaBlending) {
  45142. return false;
  45143. }
  45144. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45145. };
  45146. /**
  45147. * Specifies if the mesh will require alpha blending.
  45148. * @param mesh - BJS mesh.
  45149. */
  45150. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45151. if (this._disableAlphaBlending) {
  45152. return false;
  45153. }
  45154. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45155. };
  45156. /**
  45157. * Specifies whether or not this material should be rendered in alpha test mode.
  45158. */
  45159. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45160. if (this._forceAlphaTest) {
  45161. return true;
  45162. }
  45163. if (this._linkRefractionWithTransparency) {
  45164. return false;
  45165. }
  45166. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45167. };
  45168. /**
  45169. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45170. */
  45171. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45172. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45173. };
  45174. /**
  45175. * Gets the texture used for the alpha test.
  45176. */
  45177. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45178. return this._albedoTexture;
  45179. };
  45180. /**
  45181. * Specifies that the submesh is ready to be used.
  45182. * @param mesh - BJS mesh.
  45183. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45184. * @param useInstances - Specifies that instances should be used.
  45185. * @returns - boolean indicating that the submesh is ready or not.
  45186. */
  45187. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45188. if (subMesh.effect && this.isFrozen) {
  45189. if (this._wasPreviouslyReady) {
  45190. return true;
  45191. }
  45192. }
  45193. if (!subMesh._materialDefines) {
  45194. subMesh._materialDefines = new PBRMaterialDefines();
  45195. }
  45196. var defines = subMesh._materialDefines;
  45197. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45198. if (defines._renderId === this.getScene().getRenderId()) {
  45199. return true;
  45200. }
  45201. }
  45202. var scene = this.getScene();
  45203. var engine = scene.getEngine();
  45204. if (defines._areTexturesDirty) {
  45205. if (scene.texturesEnabled) {
  45206. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45207. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45208. return false;
  45209. }
  45210. }
  45211. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45212. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45213. return false;
  45214. }
  45215. }
  45216. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45217. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45218. return false;
  45219. }
  45220. }
  45221. var reflectionTexture = this._getReflectionTexture();
  45222. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45223. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45224. return false;
  45225. }
  45226. }
  45227. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45228. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45229. return false;
  45230. }
  45231. }
  45232. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45233. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45234. return false;
  45235. }
  45236. }
  45237. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45238. if (this._metallicTexture) {
  45239. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45240. return false;
  45241. }
  45242. }
  45243. else if (this._reflectivityTexture) {
  45244. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45245. return false;
  45246. }
  45247. }
  45248. if (this._microSurfaceTexture) {
  45249. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45250. return false;
  45251. }
  45252. }
  45253. }
  45254. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45255. // Bump texture cannot be not blocking.
  45256. if (!this._bumpTexture.isReady()) {
  45257. return false;
  45258. }
  45259. }
  45260. var refractionTexture = this._getRefractionTexture();
  45261. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45262. if (!refractionTexture.isReadyOrNotBlocking()) {
  45263. return false;
  45264. }
  45265. }
  45266. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45267. // This is blocking.
  45268. if (!this._environmentBRDFTexture.isReady()) {
  45269. return false;
  45270. }
  45271. }
  45272. }
  45273. }
  45274. if (defines._areImageProcessingDirty) {
  45275. if (!this._imageProcessingConfiguration.isReady()) {
  45276. return false;
  45277. }
  45278. }
  45279. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45280. mesh.createNormals(true);
  45281. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45282. }
  45283. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45284. if (effect) {
  45285. scene.resetCachedMaterial();
  45286. subMesh.setEffect(effect, defines);
  45287. this.buildUniformLayout();
  45288. }
  45289. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45290. return false;
  45291. }
  45292. defines._renderId = scene.getRenderId();
  45293. this._wasPreviouslyReady = true;
  45294. return true;
  45295. };
  45296. /**
  45297. * Specifies if the material uses metallic roughness workflow.
  45298. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45299. */
  45300. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45301. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45302. return true;
  45303. }
  45304. return false;
  45305. };
  45306. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45307. if (onCompiled === void 0) { onCompiled = null; }
  45308. if (onError === void 0) { onError = null; }
  45309. if (useInstances === void 0) { useInstances = null; }
  45310. if (useClipPlane === void 0) { useClipPlane = null; }
  45311. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45312. if (!defines.isDirty) {
  45313. return null;
  45314. }
  45315. defines.markAsProcessed();
  45316. var scene = this.getScene();
  45317. var engine = scene.getEngine();
  45318. // Fallbacks
  45319. var fallbacks = new BABYLON.EffectFallbacks();
  45320. var fallbackRank = 0;
  45321. if (defines.USESPHERICALINVERTEX) {
  45322. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45323. }
  45324. if (defines.FOG) {
  45325. fallbacks.addFallback(fallbackRank, "FOG");
  45326. }
  45327. if (defines.SPECULARAA) {
  45328. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45329. }
  45330. if (defines.POINTSIZE) {
  45331. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45332. }
  45333. if (defines.LOGARITHMICDEPTH) {
  45334. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45335. }
  45336. if (defines.PARALLAX) {
  45337. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45338. }
  45339. if (defines.PARALLAXOCCLUSION) {
  45340. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45341. }
  45342. if (defines.ENVIRONMENTBRDF) {
  45343. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45344. }
  45345. if (defines.TANGENT) {
  45346. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45347. }
  45348. if (defines.BUMP) {
  45349. fallbacks.addFallback(fallbackRank++, "BUMP");
  45350. }
  45351. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45352. if (defines.SPECULARTERM) {
  45353. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45354. }
  45355. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45356. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45357. }
  45358. if (defines.LIGHTMAP) {
  45359. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45360. }
  45361. if (defines.NORMAL) {
  45362. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45363. }
  45364. if (defines.AMBIENT) {
  45365. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45366. }
  45367. if (defines.EMISSIVE) {
  45368. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45369. }
  45370. if (defines.VERTEXCOLOR) {
  45371. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45372. }
  45373. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45374. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45375. }
  45376. if (defines.MORPHTARGETS) {
  45377. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45378. }
  45379. //Attributes
  45380. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45381. if (defines.NORMAL) {
  45382. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45383. }
  45384. if (defines.TANGENT) {
  45385. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45386. }
  45387. if (defines.UV1) {
  45388. attribs.push(BABYLON.VertexBuffer.UVKind);
  45389. }
  45390. if (defines.UV2) {
  45391. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45392. }
  45393. if (defines.VERTEXCOLOR) {
  45394. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45395. }
  45396. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45397. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45398. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45399. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45400. "vFogInfos", "vFogColor", "pointSize",
  45401. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45402. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45403. "mBones",
  45404. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45405. "vLightingIntensity",
  45406. "logarithmicDepthConstant",
  45407. "vSphericalX", "vSphericalY", "vSphericalZ",
  45408. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45409. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45410. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45411. "vTangentSpaceParams"
  45412. ];
  45413. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45414. "bumpSampler", "lightmapSampler", "opacitySampler",
  45415. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45416. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45417. "microSurfaceSampler", "environmentBrdfSampler"];
  45418. var uniformBuffers = ["Material", "Scene"];
  45419. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45420. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45421. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45422. uniformsNames: uniforms,
  45423. uniformBuffersNames: uniformBuffers,
  45424. samplers: samplers,
  45425. defines: defines,
  45426. maxSimultaneousLights: this._maxSimultaneousLights
  45427. });
  45428. var join = defines.toString();
  45429. return engine.createEffect("pbr", {
  45430. attributes: attribs,
  45431. uniformsNames: uniforms,
  45432. uniformBuffersNames: uniformBuffers,
  45433. samplers: samplers,
  45434. defines: join,
  45435. fallbacks: fallbacks,
  45436. onCompiled: onCompiled,
  45437. onError: onError,
  45438. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45439. }, engine);
  45440. };
  45441. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45442. if (useInstances === void 0) { useInstances = null; }
  45443. if (useClipPlane === void 0) { useClipPlane = null; }
  45444. var scene = this.getScene();
  45445. var engine = scene.getEngine();
  45446. // Lights
  45447. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45448. defines._needNormals = true;
  45449. // Textures
  45450. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45451. if (defines._areTexturesDirty) {
  45452. defines._needUVs = false;
  45453. if (scene.texturesEnabled) {
  45454. if (scene.getEngine().getCaps().textureLOD) {
  45455. defines.LODBASEDMICROSFURACE = true;
  45456. }
  45457. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45458. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45459. }
  45460. else {
  45461. defines.ALBEDO = false;
  45462. }
  45463. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45465. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45466. }
  45467. else {
  45468. defines.AMBIENT = false;
  45469. }
  45470. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45472. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45473. }
  45474. else {
  45475. defines.OPACITY = false;
  45476. }
  45477. var reflectionTexture = this._getReflectionTexture();
  45478. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45479. defines.REFLECTION = true;
  45480. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45481. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45482. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45483. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45484. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45485. defines.INVERTCUBICMAP = true;
  45486. }
  45487. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45488. switch (reflectionTexture.coordinatesMode) {
  45489. case BABYLON.Texture.EXPLICIT_MODE:
  45490. defines.REFLECTIONMAP_EXPLICIT = true;
  45491. break;
  45492. case BABYLON.Texture.PLANAR_MODE:
  45493. defines.REFLECTIONMAP_PLANAR = true;
  45494. break;
  45495. case BABYLON.Texture.PROJECTION_MODE:
  45496. defines.REFLECTIONMAP_PROJECTION = true;
  45497. break;
  45498. case BABYLON.Texture.SKYBOX_MODE:
  45499. defines.REFLECTIONMAP_SKYBOX = true;
  45500. break;
  45501. case BABYLON.Texture.SPHERICAL_MODE:
  45502. defines.REFLECTIONMAP_SPHERICAL = true;
  45503. break;
  45504. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45505. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45506. break;
  45507. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45508. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45509. break;
  45510. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45511. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45512. break;
  45513. case BABYLON.Texture.CUBIC_MODE:
  45514. case BABYLON.Texture.INVCUBIC_MODE:
  45515. default:
  45516. defines.REFLECTIONMAP_CUBIC = true;
  45517. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45518. break;
  45519. }
  45520. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45521. if (reflectionTexture.sphericalPolynomial) {
  45522. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45523. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45524. defines.USESPHERICALINVERTEX = false;
  45525. }
  45526. else {
  45527. defines.USESPHERICALINVERTEX = true;
  45528. }
  45529. }
  45530. }
  45531. }
  45532. else {
  45533. defines.REFLECTION = false;
  45534. defines.REFLECTIONMAP_3D = false;
  45535. defines.REFLECTIONMAP_SPHERICAL = false;
  45536. defines.REFLECTIONMAP_PLANAR = false;
  45537. defines.REFLECTIONMAP_CUBIC = false;
  45538. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45539. defines.REFLECTIONMAP_PROJECTION = false;
  45540. defines.REFLECTIONMAP_SKYBOX = false;
  45541. defines.REFLECTIONMAP_EXPLICIT = false;
  45542. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45543. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45544. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45545. defines.INVERTCUBICMAP = false;
  45546. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45547. defines.USESPHERICALINVERTEX = false;
  45548. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45549. defines.LODINREFLECTIONALPHA = false;
  45550. defines.GAMMAREFLECTION = false;
  45551. defines.RGBDREFLECTION = false;
  45552. }
  45553. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45554. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45555. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45556. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45557. }
  45558. else {
  45559. defines.LIGHTMAP = false;
  45560. }
  45561. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45562. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45563. }
  45564. else {
  45565. defines.EMISSIVE = false;
  45566. }
  45567. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45568. if (this._metallicTexture) {
  45569. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45570. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45571. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45572. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45573. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45574. }
  45575. else if (this._reflectivityTexture) {
  45576. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45577. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45578. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45579. }
  45580. else {
  45581. defines.REFLECTIVITY = false;
  45582. }
  45583. if (this._microSurfaceTexture) {
  45584. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45585. }
  45586. else {
  45587. defines.MICROSURFACEMAP = false;
  45588. }
  45589. }
  45590. else {
  45591. defines.REFLECTIVITY = false;
  45592. defines.MICROSURFACEMAP = false;
  45593. }
  45594. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45595. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45596. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45597. defines.PARALLAX = true;
  45598. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45599. }
  45600. else {
  45601. defines.PARALLAX = false;
  45602. }
  45603. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45604. }
  45605. else {
  45606. defines.BUMP = false;
  45607. }
  45608. var refractionTexture = this._getRefractionTexture();
  45609. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45610. defines.REFRACTION = true;
  45611. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45612. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45613. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45614. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45615. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45616. if (this._linkRefractionWithTransparency) {
  45617. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45618. }
  45619. }
  45620. else {
  45621. defines.REFRACTION = false;
  45622. }
  45623. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45624. defines.ENVIRONMENTBRDF = true;
  45625. }
  45626. else {
  45627. defines.ENVIRONMENTBRDF = false;
  45628. }
  45629. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45630. defines.ALPHAFROMALBEDO = true;
  45631. }
  45632. else {
  45633. defines.ALPHAFROMALBEDO = false;
  45634. }
  45635. }
  45636. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45637. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45638. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45639. if (!this.backFaceCulling && this._twoSidedLighting) {
  45640. defines.TWOSIDEDLIGHTING = true;
  45641. }
  45642. else {
  45643. defines.TWOSIDEDLIGHTING = false;
  45644. }
  45645. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45646. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45647. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45648. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45649. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45650. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45651. }
  45652. if (defines._areImageProcessingDirty) {
  45653. this._imageProcessingConfiguration.prepareDefines(defines);
  45654. }
  45655. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45656. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45657. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45658. // Misc.
  45659. if (defines._areMiscDirty) {
  45660. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45661. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45662. }
  45663. // Values that need to be evaluated on every frame
  45664. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45665. // Attribs
  45666. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45667. };
  45668. /**
  45669. * Force shader compilation
  45670. */
  45671. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45672. var _this = this;
  45673. var localOptions = __assign({ clipPlane: false }, options);
  45674. var defines = new PBRMaterialDefines();
  45675. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45676. if (effect.isReady()) {
  45677. if (onCompiled) {
  45678. onCompiled(this);
  45679. }
  45680. }
  45681. else {
  45682. effect.onCompileObservable.add(function () {
  45683. if (onCompiled) {
  45684. onCompiled(_this);
  45685. }
  45686. });
  45687. }
  45688. };
  45689. /**
  45690. * Initializes the uniform buffer layout for the shader.
  45691. */
  45692. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45693. // Order is important !
  45694. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45695. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45696. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45697. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45698. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45699. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45700. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45701. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45702. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45703. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45704. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45705. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45706. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45707. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45708. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45709. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45710. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45711. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45712. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45713. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45714. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45715. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45716. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45717. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45718. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45719. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45720. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45721. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45722. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45723. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45724. this._uniformBuffer.addUniform("pointSize", 1);
  45725. this._uniformBuffer.create();
  45726. };
  45727. /**
  45728. * Unbinds the textures.
  45729. */
  45730. PBRBaseMaterial.prototype.unbind = function () {
  45731. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45732. this._uniformBuffer.setTexture("reflectionSampler", null);
  45733. }
  45734. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45735. this._uniformBuffer.setTexture("refractionSampler", null);
  45736. }
  45737. _super.prototype.unbind.call(this);
  45738. };
  45739. /**
  45740. * Binds the submesh data.
  45741. * @param world - The world matrix.
  45742. * @param mesh - The BJS mesh.
  45743. * @param subMesh - A submesh of the BJS mesh.
  45744. */
  45745. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45746. var scene = this.getScene();
  45747. var defines = subMesh._materialDefines;
  45748. if (!defines) {
  45749. return;
  45750. }
  45751. var effect = subMesh.effect;
  45752. if (!effect) {
  45753. return;
  45754. }
  45755. this._activeEffect = effect;
  45756. // Matrices
  45757. this.bindOnlyWorldMatrix(world);
  45758. // Normal Matrix
  45759. if (defines.OBJECTSPACE_NORMALMAP) {
  45760. world.toNormalMatrix(this._normalMatrix);
  45761. this.bindOnlyNormalMatrix(this._normalMatrix);
  45762. }
  45763. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45764. // Bones
  45765. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45766. var reflectionTexture = null;
  45767. if (mustRebind) {
  45768. this._uniformBuffer.bindToEffect(effect, "Material");
  45769. this.bindViewProjection(effect);
  45770. reflectionTexture = this._getReflectionTexture();
  45771. var refractionTexture = this._getRefractionTexture();
  45772. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45773. // Texture uniforms
  45774. if (scene.texturesEnabled) {
  45775. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45776. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45777. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45778. }
  45779. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45780. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45781. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45782. }
  45783. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45784. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45785. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45786. }
  45787. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45788. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45789. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45790. if (reflectionTexture.boundingBoxSize) {
  45791. var cubeTexture = reflectionTexture;
  45792. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45793. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45794. }
  45795. var polynomials = reflectionTexture.sphericalPolynomial;
  45796. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45797. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45798. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45799. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45800. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45801. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45802. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45803. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45804. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45805. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45806. }
  45807. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45808. }
  45809. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45810. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45811. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45812. }
  45813. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45814. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45815. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45816. }
  45817. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45818. if (this._metallicTexture) {
  45819. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45820. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45821. }
  45822. else if (this._reflectivityTexture) {
  45823. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45824. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45825. }
  45826. if (this._microSurfaceTexture) {
  45827. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45828. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45829. }
  45830. }
  45831. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45832. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45833. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45834. if (scene._mirroredCameraPosition) {
  45835. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45836. }
  45837. else {
  45838. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45839. }
  45840. }
  45841. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45842. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45843. var depth = 1.0;
  45844. if (!refractionTexture.isCube) {
  45845. if (refractionTexture.depth) {
  45846. depth = refractionTexture.depth;
  45847. }
  45848. }
  45849. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45850. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45851. }
  45852. }
  45853. // Point size
  45854. if (this.pointsCloud) {
  45855. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45856. }
  45857. // Colors
  45858. if (defines.METALLICWORKFLOW) {
  45859. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45860. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45861. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45862. }
  45863. else {
  45864. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45865. }
  45866. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45867. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45868. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45869. // Misc
  45870. this._lightingInfos.x = this._directIntensity;
  45871. this._lightingInfos.y = this._emissiveIntensity;
  45872. this._lightingInfos.z = this._environmentIntensity;
  45873. this._lightingInfos.w = this._specularIntensity;
  45874. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45875. }
  45876. // Textures
  45877. if (scene.texturesEnabled) {
  45878. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45879. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45880. }
  45881. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45882. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45883. }
  45884. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45885. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45886. }
  45887. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45888. if (defines.LODBASEDMICROSFURACE) {
  45889. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45890. }
  45891. else {
  45892. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45893. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45894. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45895. }
  45896. }
  45897. if (defines.ENVIRONMENTBRDF) {
  45898. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45899. }
  45900. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45901. if (defines.LODBASEDMICROSFURACE) {
  45902. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45903. }
  45904. else {
  45905. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45906. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45907. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45908. }
  45909. }
  45910. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45911. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45912. }
  45913. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45914. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45915. }
  45916. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45917. if (this._metallicTexture) {
  45918. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45919. }
  45920. else if (this._reflectivityTexture) {
  45921. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45922. }
  45923. if (this._microSurfaceTexture) {
  45924. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45925. }
  45926. }
  45927. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45928. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45929. }
  45930. }
  45931. // Clip plane
  45932. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45933. // Colors
  45934. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45935. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45936. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45937. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45938. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45939. }
  45940. if (mustRebind || !this.isFrozen) {
  45941. // Lights
  45942. if (scene.lightsEnabled && !this._disableLighting) {
  45943. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45944. }
  45945. // View
  45946. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45947. this.bindView(effect);
  45948. }
  45949. // Fog
  45950. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45951. // Morph targets
  45952. if (defines.NUM_MORPH_INFLUENCERS) {
  45953. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45954. }
  45955. // image processing
  45956. this._imageProcessingConfiguration.bind(this._activeEffect);
  45957. // Log. depth
  45958. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45959. }
  45960. this._uniformBuffer.update();
  45961. this._afterBind(mesh, this._activeEffect);
  45962. };
  45963. /**
  45964. * Returns the animatable textures.
  45965. * @returns - Array of animatable textures.
  45966. */
  45967. PBRBaseMaterial.prototype.getAnimatables = function () {
  45968. var results = [];
  45969. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45970. results.push(this._albedoTexture);
  45971. }
  45972. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45973. results.push(this._ambientTexture);
  45974. }
  45975. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45976. results.push(this._opacityTexture);
  45977. }
  45978. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45979. results.push(this._reflectionTexture);
  45980. }
  45981. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45982. results.push(this._emissiveTexture);
  45983. }
  45984. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45985. results.push(this._metallicTexture);
  45986. }
  45987. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45988. results.push(this._reflectivityTexture);
  45989. }
  45990. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45991. results.push(this._bumpTexture);
  45992. }
  45993. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45994. results.push(this._lightmapTexture);
  45995. }
  45996. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45997. results.push(this._refractionTexture);
  45998. }
  45999. return results;
  46000. };
  46001. /**
  46002. * Returns the texture used for reflections.
  46003. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46004. */
  46005. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46006. if (this._reflectionTexture) {
  46007. return this._reflectionTexture;
  46008. }
  46009. return this.getScene().environmentTexture;
  46010. };
  46011. /**
  46012. * Returns the texture used for refraction or null if none is used.
  46013. * @returns - Refection texture if present. If no refraction texture and refraction
  46014. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46015. */
  46016. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46017. if (this._refractionTexture) {
  46018. return this._refractionTexture;
  46019. }
  46020. if (this._linkRefractionWithTransparency) {
  46021. return this.getScene().environmentTexture;
  46022. }
  46023. return null;
  46024. };
  46025. /**
  46026. * Disposes the resources of the material.
  46027. * @param forceDisposeEffect - Forces the disposal of effects.
  46028. * @param forceDisposeTextures - Forces the disposal of all textures.
  46029. */
  46030. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46031. if (forceDisposeTextures) {
  46032. if (this._albedoTexture) {
  46033. this._albedoTexture.dispose();
  46034. }
  46035. if (this._ambientTexture) {
  46036. this._ambientTexture.dispose();
  46037. }
  46038. if (this._opacityTexture) {
  46039. this._opacityTexture.dispose();
  46040. }
  46041. if (this._reflectionTexture) {
  46042. this._reflectionTexture.dispose();
  46043. }
  46044. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46045. this._environmentBRDFTexture.dispose();
  46046. }
  46047. if (this._emissiveTexture) {
  46048. this._emissiveTexture.dispose();
  46049. }
  46050. if (this._metallicTexture) {
  46051. this._metallicTexture.dispose();
  46052. }
  46053. if (this._reflectivityTexture) {
  46054. this._reflectivityTexture.dispose();
  46055. }
  46056. if (this._bumpTexture) {
  46057. this._bumpTexture.dispose();
  46058. }
  46059. if (this._lightmapTexture) {
  46060. this._lightmapTexture.dispose();
  46061. }
  46062. if (this._refractionTexture) {
  46063. this._refractionTexture.dispose();
  46064. }
  46065. }
  46066. this._renderTargets.dispose();
  46067. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46068. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46069. }
  46070. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46071. };
  46072. /**
  46073. * Stores the reflectivity values based on metallic roughness workflow.
  46074. */
  46075. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46076. __decorate([
  46077. BABYLON.serializeAsImageProcessingConfiguration()
  46078. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46079. __decorate([
  46080. BABYLON.serialize()
  46081. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46082. __decorate([
  46083. BABYLON.serialize()
  46084. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46085. return PBRBaseMaterial;
  46086. }(BABYLON.PushMaterial));
  46087. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46088. })(BABYLON || (BABYLON = {}));
  46089. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46090. var BABYLON;
  46091. (function (BABYLON) {
  46092. /**
  46093. * The Physically based simple base material of BJS.
  46094. *
  46095. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46096. * It is used as the base class for both the specGloss and metalRough conventions.
  46097. */
  46098. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46099. __extends(PBRBaseSimpleMaterial, _super);
  46100. /**
  46101. * Instantiates a new PBRMaterial instance.
  46102. *
  46103. * @param name The material name
  46104. * @param scene The scene the material will be use in.
  46105. */
  46106. function PBRBaseSimpleMaterial(name, scene) {
  46107. var _this = _super.call(this, name, scene) || this;
  46108. /**
  46109. * Number of Simultaneous lights allowed on the material.
  46110. */
  46111. _this.maxSimultaneousLights = 4;
  46112. /**
  46113. * If sets to true, disables all the lights affecting the material.
  46114. */
  46115. _this.disableLighting = false;
  46116. /**
  46117. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46118. */
  46119. _this.invertNormalMapX = false;
  46120. /**
  46121. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46122. */
  46123. _this.invertNormalMapY = false;
  46124. /**
  46125. * Emissivie color used to self-illuminate the model.
  46126. */
  46127. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46128. /**
  46129. * Occlusion Channel Strenght.
  46130. */
  46131. _this.occlusionStrength = 1.0;
  46132. _this.useLightmapAsShadowmap = false;
  46133. _this._useAlphaFromAlbedoTexture = true;
  46134. _this._useAmbientInGrayScale = true;
  46135. return _this;
  46136. }
  46137. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46138. /**
  46139. * Gets the current double sided mode.
  46140. */
  46141. get: function () {
  46142. return this._twoSidedLighting;
  46143. },
  46144. /**
  46145. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46146. */
  46147. set: function (value) {
  46148. if (this._twoSidedLighting === value) {
  46149. return;
  46150. }
  46151. this._twoSidedLighting = value;
  46152. this.backFaceCulling = !value;
  46153. this._markAllSubMeshesAsTexturesDirty();
  46154. },
  46155. enumerable: true,
  46156. configurable: true
  46157. });
  46158. /**
  46159. * Return the active textures of the material.
  46160. */
  46161. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46162. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46163. if (this.environmentTexture) {
  46164. activeTextures.push(this.environmentTexture);
  46165. }
  46166. if (this.normalTexture) {
  46167. activeTextures.push(this.normalTexture);
  46168. }
  46169. if (this.emissiveTexture) {
  46170. activeTextures.push(this.emissiveTexture);
  46171. }
  46172. if (this.occlusionTexture) {
  46173. activeTextures.push(this.occlusionTexture);
  46174. }
  46175. if (this.lightmapTexture) {
  46176. activeTextures.push(this.lightmapTexture);
  46177. }
  46178. return activeTextures;
  46179. };
  46180. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46181. if (_super.prototype.hasTexture.call(this, texture)) {
  46182. return true;
  46183. }
  46184. if (this.lightmapTexture === texture) {
  46185. return true;
  46186. }
  46187. return false;
  46188. };
  46189. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46190. return "PBRBaseSimpleMaterial";
  46191. };
  46192. __decorate([
  46193. BABYLON.serialize(),
  46194. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46195. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46196. __decorate([
  46197. BABYLON.serialize(),
  46198. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46199. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46200. __decorate([
  46201. BABYLON.serializeAsTexture(),
  46202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46203. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46204. __decorate([
  46205. BABYLON.serialize(),
  46206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46207. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46208. __decorate([
  46209. BABYLON.serialize(),
  46210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46211. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46212. __decorate([
  46213. BABYLON.serializeAsTexture(),
  46214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46215. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46216. __decorate([
  46217. BABYLON.serializeAsColor3("emissive"),
  46218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46219. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46220. __decorate([
  46221. BABYLON.serializeAsTexture(),
  46222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46223. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46224. __decorate([
  46225. BABYLON.serialize(),
  46226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46227. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46228. __decorate([
  46229. BABYLON.serializeAsTexture(),
  46230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46231. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46232. __decorate([
  46233. BABYLON.serialize(),
  46234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46235. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46236. __decorate([
  46237. BABYLON.serialize()
  46238. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46239. __decorate([
  46240. BABYLON.serializeAsTexture(),
  46241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46242. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46243. __decorate([
  46244. BABYLON.serialize(),
  46245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46246. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46247. return PBRBaseSimpleMaterial;
  46248. }(BABYLON.PBRBaseMaterial));
  46249. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46250. })(BABYLON || (BABYLON = {}));
  46251. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46252. var BABYLON;
  46253. (function (BABYLON) {
  46254. /**
  46255. * The Physically based material of BJS.
  46256. *
  46257. * This offers the main features of a standard PBR material.
  46258. * For more information, please refer to the documentation :
  46259. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46260. */
  46261. var PBRMaterial = /** @class */ (function (_super) {
  46262. __extends(PBRMaterial, _super);
  46263. /**
  46264. * Instantiates a new PBRMaterial instance.
  46265. *
  46266. * @param name The material name
  46267. * @param scene The scene the material will be use in.
  46268. */
  46269. function PBRMaterial(name, scene) {
  46270. var _this = _super.call(this, name, scene) || this;
  46271. /**
  46272. * Intensity of the direct lights e.g. the four lights available in your scene.
  46273. * This impacts both the direct diffuse and specular highlights.
  46274. */
  46275. _this.directIntensity = 1.0;
  46276. /**
  46277. * Intensity of the emissive part of the material.
  46278. * This helps controlling the emissive effect without modifying the emissive color.
  46279. */
  46280. _this.emissiveIntensity = 1.0;
  46281. /**
  46282. * Intensity of the environment e.g. how much the environment will light the object
  46283. * either through harmonics for rough material or through the refelction for shiny ones.
  46284. */
  46285. _this.environmentIntensity = 1.0;
  46286. /**
  46287. * This is a special control allowing the reduction of the specular highlights coming from the
  46288. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46289. */
  46290. _this.specularIntensity = 1.0;
  46291. /**
  46292. * Debug Control allowing disabling the bump map on this material.
  46293. */
  46294. _this.disableBumpMap = false;
  46295. /**
  46296. * AKA Occlusion Texture Intensity in other nomenclature.
  46297. */
  46298. _this.ambientTextureStrength = 1.0;
  46299. /**
  46300. * The color of a material in ambient lighting.
  46301. */
  46302. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46303. /**
  46304. * AKA Diffuse Color in other nomenclature.
  46305. */
  46306. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46307. /**
  46308. * AKA Specular Color in other nomenclature.
  46309. */
  46310. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46311. /**
  46312. * The color reflected from the material.
  46313. */
  46314. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46315. /**
  46316. * The color emitted from the material.
  46317. */
  46318. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46319. /**
  46320. * AKA Glossiness in other nomenclature.
  46321. */
  46322. _this.microSurface = 1.0;
  46323. /**
  46324. * source material index of refraction (IOR)' / 'destination material IOR.
  46325. */
  46326. _this.indexOfRefraction = 0.66;
  46327. /**
  46328. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46329. */
  46330. _this.invertRefractionY = false;
  46331. /**
  46332. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46333. * Materials half opaque for instance using refraction could benefit from this control.
  46334. */
  46335. _this.linkRefractionWithTransparency = false;
  46336. _this.useLightmapAsShadowmap = false;
  46337. /**
  46338. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46339. */
  46340. _this.useAlphaFromAlbedoTexture = false;
  46341. /**
  46342. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46343. */
  46344. _this.forceAlphaTest = false;
  46345. /**
  46346. * Defines the alpha limits in alpha test mode.
  46347. */
  46348. _this.alphaCutOff = 0.4;
  46349. /**
  46350. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46351. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46352. */
  46353. _this.useSpecularOverAlpha = true;
  46354. /**
  46355. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46356. */
  46357. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46358. /**
  46359. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46360. */
  46361. _this.useRoughnessFromMetallicTextureAlpha = true;
  46362. /**
  46363. * Specifies if the metallic texture contains the roughness information in its green channel.
  46364. */
  46365. _this.useRoughnessFromMetallicTextureGreen = false;
  46366. /**
  46367. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46368. */
  46369. _this.useMetallnessFromMetallicTextureBlue = false;
  46370. /**
  46371. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46372. */
  46373. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46374. /**
  46375. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46376. */
  46377. _this.useAmbientInGrayScale = false;
  46378. /**
  46379. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46380. * The material will try to infer what glossiness each pixel should be.
  46381. */
  46382. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46383. /**
  46384. * BJS is using an harcoded light falloff based on a manually sets up range.
  46385. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46386. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46387. */
  46388. _this.usePhysicalLightFalloff = true;
  46389. /**
  46390. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46391. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46392. */
  46393. _this.useRadianceOverAlpha = true;
  46394. /**
  46395. * Allows using an object space normal map (instead of tangent space).
  46396. */
  46397. _this.useObjectSpaceNormalMap = false;
  46398. /**
  46399. * Allows using the bump map in parallax mode.
  46400. */
  46401. _this.useParallax = false;
  46402. /**
  46403. * Allows using the bump map in parallax occlusion mode.
  46404. */
  46405. _this.useParallaxOcclusion = false;
  46406. /**
  46407. * Controls the scale bias of the parallax mode.
  46408. */
  46409. _this.parallaxScaleBias = 0.05;
  46410. /**
  46411. * If sets to true, disables all the lights affecting the material.
  46412. */
  46413. _this.disableLighting = false;
  46414. /**
  46415. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46416. */
  46417. _this.forceIrradianceInFragment = false;
  46418. /**
  46419. * Number of Simultaneous lights allowed on the material.
  46420. */
  46421. _this.maxSimultaneousLights = 4;
  46422. /**
  46423. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46424. */
  46425. _this.invertNormalMapX = false;
  46426. /**
  46427. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46428. */
  46429. _this.invertNormalMapY = false;
  46430. /**
  46431. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46432. */
  46433. _this.twoSidedLighting = false;
  46434. /**
  46435. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46436. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46437. */
  46438. _this.useAlphaFresnel = false;
  46439. /**
  46440. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46441. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46442. */
  46443. _this.useLinearAlphaFresnel = false;
  46444. /**
  46445. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46446. * And/Or occlude the blended part.
  46447. */
  46448. _this.environmentBRDFTexture = null;
  46449. /**
  46450. * Force normal to face away from face.
  46451. */
  46452. _this.forceNormalForward = false;
  46453. /**
  46454. * Enables specular anti aliasing in the PBR shader.
  46455. * It will both interacts on the Geometry for analytical and IBL lighting.
  46456. * It also prefilter the roughness map based on the bump values.
  46457. */
  46458. _this.enableSpecularAntiAliasing = false;
  46459. /**
  46460. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46461. * makes the reflect vector face the model (under horizon).
  46462. */
  46463. _this.useHorizonOcclusion = true;
  46464. /**
  46465. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46466. * too much the area relying on ambient texture to define their ambient occlusion.
  46467. */
  46468. _this.useRadianceOcclusion = true;
  46469. /**
  46470. * If set to true, no lighting calculations will be applied.
  46471. */
  46472. _this.unlit = false;
  46473. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46474. return _this;
  46475. }
  46476. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46477. /**
  46478. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46479. */
  46480. get: function () {
  46481. return this._PBRMATERIAL_OPAQUE;
  46482. },
  46483. enumerable: true,
  46484. configurable: true
  46485. });
  46486. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46487. /**
  46488. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46489. */
  46490. get: function () {
  46491. return this._PBRMATERIAL_ALPHATEST;
  46492. },
  46493. enumerable: true,
  46494. configurable: true
  46495. });
  46496. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46497. /**
  46498. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46499. */
  46500. get: function () {
  46501. return this._PBRMATERIAL_ALPHABLEND;
  46502. },
  46503. enumerable: true,
  46504. configurable: true
  46505. });
  46506. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46507. /**
  46508. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46509. * They are also discarded below the alpha cutoff threshold to improve performances.
  46510. */
  46511. get: function () {
  46512. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46513. },
  46514. enumerable: true,
  46515. configurable: true
  46516. });
  46517. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46518. /**
  46519. * Gets the image processing configuration used either in this material.
  46520. */
  46521. get: function () {
  46522. return this._imageProcessingConfiguration;
  46523. },
  46524. /**
  46525. * Sets the Default image processing configuration used either in the this material.
  46526. *
  46527. * If sets to null, the scene one is in use.
  46528. */
  46529. set: function (value) {
  46530. this._attachImageProcessingConfiguration(value);
  46531. // Ensure the effect will be rebuilt.
  46532. this._markAllSubMeshesAsTexturesDirty();
  46533. },
  46534. enumerable: true,
  46535. configurable: true
  46536. });
  46537. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46538. /**
  46539. * Gets wether the color curves effect is enabled.
  46540. */
  46541. get: function () {
  46542. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46543. },
  46544. /**
  46545. * Sets wether the color curves effect is enabled.
  46546. */
  46547. set: function (value) {
  46548. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46549. },
  46550. enumerable: true,
  46551. configurable: true
  46552. });
  46553. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46554. /**
  46555. * Gets wether the color grading effect is enabled.
  46556. */
  46557. get: function () {
  46558. return this.imageProcessingConfiguration.colorGradingEnabled;
  46559. },
  46560. /**
  46561. * Gets wether the color grading effect is enabled.
  46562. */
  46563. set: function (value) {
  46564. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46565. },
  46566. enumerable: true,
  46567. configurable: true
  46568. });
  46569. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46570. /**
  46571. * Gets wether tonemapping is enabled or not.
  46572. */
  46573. get: function () {
  46574. return this._imageProcessingConfiguration.toneMappingEnabled;
  46575. },
  46576. /**
  46577. * Sets wether tonemapping is enabled or not
  46578. */
  46579. set: function (value) {
  46580. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46581. },
  46582. enumerable: true,
  46583. configurable: true
  46584. });
  46585. ;
  46586. ;
  46587. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46588. /**
  46589. * The camera exposure used on this material.
  46590. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46591. * This corresponds to a photographic exposure.
  46592. */
  46593. get: function () {
  46594. return this._imageProcessingConfiguration.exposure;
  46595. },
  46596. /**
  46597. * The camera exposure used on this material.
  46598. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46599. * This corresponds to a photographic exposure.
  46600. */
  46601. set: function (value) {
  46602. this._imageProcessingConfiguration.exposure = value;
  46603. },
  46604. enumerable: true,
  46605. configurable: true
  46606. });
  46607. ;
  46608. ;
  46609. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46610. /**
  46611. * Gets The camera contrast used on this material.
  46612. */
  46613. get: function () {
  46614. return this._imageProcessingConfiguration.contrast;
  46615. },
  46616. /**
  46617. * Sets The camera contrast used on this material.
  46618. */
  46619. set: function (value) {
  46620. this._imageProcessingConfiguration.contrast = value;
  46621. },
  46622. enumerable: true,
  46623. configurable: true
  46624. });
  46625. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46626. /**
  46627. * Gets the Color Grading 2D Lookup Texture.
  46628. */
  46629. get: function () {
  46630. return this._imageProcessingConfiguration.colorGradingTexture;
  46631. },
  46632. /**
  46633. * Sets the Color Grading 2D Lookup Texture.
  46634. */
  46635. set: function (value) {
  46636. this._imageProcessingConfiguration.colorGradingTexture = value;
  46637. },
  46638. enumerable: true,
  46639. configurable: true
  46640. });
  46641. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46642. /**
  46643. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46644. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46645. * 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;
  46646. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46647. */
  46648. get: function () {
  46649. return this._imageProcessingConfiguration.colorCurves;
  46650. },
  46651. /**
  46652. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46653. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46654. * 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;
  46655. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46656. */
  46657. set: function (value) {
  46658. this._imageProcessingConfiguration.colorCurves = value;
  46659. },
  46660. enumerable: true,
  46661. configurable: true
  46662. });
  46663. /**
  46664. * Returns the name of this material class.
  46665. */
  46666. PBRMaterial.prototype.getClassName = function () {
  46667. return "PBRMaterial";
  46668. };
  46669. /**
  46670. * Returns an array of the actively used textures.
  46671. * @returns - Array of BaseTextures
  46672. */
  46673. PBRMaterial.prototype.getActiveTextures = function () {
  46674. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46675. if (this._albedoTexture) {
  46676. activeTextures.push(this._albedoTexture);
  46677. }
  46678. if (this._ambientTexture) {
  46679. activeTextures.push(this._ambientTexture);
  46680. }
  46681. if (this._opacityTexture) {
  46682. activeTextures.push(this._opacityTexture);
  46683. }
  46684. if (this._reflectionTexture) {
  46685. activeTextures.push(this._reflectionTexture);
  46686. }
  46687. if (this._emissiveTexture) {
  46688. activeTextures.push(this._emissiveTexture);
  46689. }
  46690. if (this._reflectivityTexture) {
  46691. activeTextures.push(this._reflectivityTexture);
  46692. }
  46693. if (this._metallicTexture) {
  46694. activeTextures.push(this._metallicTexture);
  46695. }
  46696. if (this._microSurfaceTexture) {
  46697. activeTextures.push(this._microSurfaceTexture);
  46698. }
  46699. if (this._bumpTexture) {
  46700. activeTextures.push(this._bumpTexture);
  46701. }
  46702. if (this._lightmapTexture) {
  46703. activeTextures.push(this._lightmapTexture);
  46704. }
  46705. if (this._refractionTexture) {
  46706. activeTextures.push(this._refractionTexture);
  46707. }
  46708. return activeTextures;
  46709. };
  46710. /**
  46711. * Checks to see if a texture is used in the material.
  46712. * @param texture - Base texture to use.
  46713. * @returns - Boolean specifying if a texture is used in the material.
  46714. */
  46715. PBRMaterial.prototype.hasTexture = function (texture) {
  46716. if (_super.prototype.hasTexture.call(this, texture)) {
  46717. return true;
  46718. }
  46719. if (this._albedoTexture === texture) {
  46720. return true;
  46721. }
  46722. if (this._ambientTexture === texture) {
  46723. return true;
  46724. }
  46725. if (this._opacityTexture === texture) {
  46726. return true;
  46727. }
  46728. if (this._reflectionTexture === texture) {
  46729. return true;
  46730. }
  46731. if (this._reflectivityTexture === texture) {
  46732. return true;
  46733. }
  46734. if (this._metallicTexture === texture) {
  46735. return true;
  46736. }
  46737. if (this._microSurfaceTexture === texture) {
  46738. return true;
  46739. }
  46740. if (this._bumpTexture === texture) {
  46741. return true;
  46742. }
  46743. if (this._lightmapTexture === texture) {
  46744. return true;
  46745. }
  46746. if (this._refractionTexture === texture) {
  46747. return true;
  46748. }
  46749. return false;
  46750. };
  46751. /**
  46752. * Makes a duplicate of the current material.
  46753. * @param name - name to use for the new material.
  46754. */
  46755. PBRMaterial.prototype.clone = function (name) {
  46756. var _this = this;
  46757. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46758. clone.id = name;
  46759. clone.name = name;
  46760. return clone;
  46761. };
  46762. /**
  46763. * Serializes this PBR Material.
  46764. * @returns - An object with the serialized material.
  46765. */
  46766. PBRMaterial.prototype.serialize = function () {
  46767. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46768. serializationObject.customType = "BABYLON.PBRMaterial";
  46769. return serializationObject;
  46770. };
  46771. // Statics
  46772. /**
  46773. * Parses a PBR Material from a serialized object.
  46774. * @param source - Serialized object.
  46775. * @param scene - BJS scene instance.
  46776. * @param rootUrl - url for the scene object
  46777. * @returns - PBRMaterial
  46778. */
  46779. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46780. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46781. };
  46782. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46783. /**
  46784. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46785. */
  46786. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46787. /**
  46788. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46789. */
  46790. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46791. /**
  46792. * 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.
  46793. * They are also discarded below the alpha cutoff threshold to improve performances.
  46794. */
  46795. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46796. __decorate([
  46797. BABYLON.serialize(),
  46798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46799. ], PBRMaterial.prototype, "directIntensity", void 0);
  46800. __decorate([
  46801. BABYLON.serialize(),
  46802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46803. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46804. __decorate([
  46805. BABYLON.serialize(),
  46806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46807. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46808. __decorate([
  46809. BABYLON.serialize(),
  46810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46811. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46812. __decorate([
  46813. BABYLON.serialize(),
  46814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46815. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46816. __decorate([
  46817. BABYLON.serializeAsTexture(),
  46818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46819. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46820. __decorate([
  46821. BABYLON.serializeAsTexture(),
  46822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46823. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46824. __decorate([
  46825. BABYLON.serialize(),
  46826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46827. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46828. __decorate([
  46829. BABYLON.serializeAsTexture(),
  46830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46831. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46832. __decorate([
  46833. BABYLON.serializeAsTexture(),
  46834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46835. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46836. __decorate([
  46837. BABYLON.serializeAsTexture(),
  46838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46839. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46840. __decorate([
  46841. BABYLON.serializeAsTexture(),
  46842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46843. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46844. __decorate([
  46845. BABYLON.serializeAsTexture(),
  46846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46847. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46848. __decorate([
  46849. BABYLON.serialize(),
  46850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46851. ], PBRMaterial.prototype, "metallic", void 0);
  46852. __decorate([
  46853. BABYLON.serialize(),
  46854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46855. ], PBRMaterial.prototype, "roughness", void 0);
  46856. __decorate([
  46857. BABYLON.serializeAsTexture(),
  46858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46859. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46860. __decorate([
  46861. BABYLON.serializeAsTexture(),
  46862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46863. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46864. __decorate([
  46865. BABYLON.serializeAsTexture(),
  46866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46867. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46868. __decorate([
  46869. BABYLON.serializeAsTexture(),
  46870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46871. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46872. __decorate([
  46873. BABYLON.serializeAsColor3("ambient"),
  46874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46875. ], PBRMaterial.prototype, "ambientColor", void 0);
  46876. __decorate([
  46877. BABYLON.serializeAsColor3("albedo"),
  46878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46879. ], PBRMaterial.prototype, "albedoColor", void 0);
  46880. __decorate([
  46881. BABYLON.serializeAsColor3("reflectivity"),
  46882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46883. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46884. __decorate([
  46885. BABYLON.serializeAsColor3("reflection"),
  46886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46887. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46888. __decorate([
  46889. BABYLON.serializeAsColor3("emissive"),
  46890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46891. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46892. __decorate([
  46893. BABYLON.serialize(),
  46894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46895. ], PBRMaterial.prototype, "microSurface", void 0);
  46896. __decorate([
  46897. BABYLON.serialize(),
  46898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46899. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46900. __decorate([
  46901. BABYLON.serialize(),
  46902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46903. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46904. __decorate([
  46905. BABYLON.serialize(),
  46906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46907. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46908. __decorate([
  46909. BABYLON.serialize(),
  46910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46911. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46912. __decorate([
  46913. BABYLON.serialize(),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46915. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46916. __decorate([
  46917. BABYLON.serialize(),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46919. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46920. __decorate([
  46921. BABYLON.serialize(),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46923. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46924. __decorate([
  46925. BABYLON.serialize(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46927. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46928. __decorate([
  46929. BABYLON.serialize(),
  46930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46931. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46932. __decorate([
  46933. BABYLON.serialize(),
  46934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46935. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46936. __decorate([
  46937. BABYLON.serialize(),
  46938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46939. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46940. __decorate([
  46941. BABYLON.serialize(),
  46942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46943. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46944. __decorate([
  46945. BABYLON.serialize(),
  46946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46947. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46948. __decorate([
  46949. BABYLON.serialize(),
  46950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46951. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46952. __decorate([
  46953. BABYLON.serialize(),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46955. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46956. __decorate([
  46957. BABYLON.serialize(),
  46958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46959. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46960. __decorate([
  46961. BABYLON.serialize(),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46963. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46964. __decorate([
  46965. BABYLON.serialize(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46967. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46968. __decorate([
  46969. BABYLON.serialize(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46971. ], PBRMaterial.prototype, "useParallax", void 0);
  46972. __decorate([
  46973. BABYLON.serialize(),
  46974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46975. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46976. __decorate([
  46977. BABYLON.serialize(),
  46978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46979. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46980. __decorate([
  46981. BABYLON.serialize(),
  46982. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46983. ], PBRMaterial.prototype, "disableLighting", void 0);
  46984. __decorate([
  46985. BABYLON.serialize(),
  46986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46987. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46988. __decorate([
  46989. BABYLON.serialize(),
  46990. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46991. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46992. __decorate([
  46993. BABYLON.serialize(),
  46994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46995. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46996. __decorate([
  46997. BABYLON.serialize(),
  46998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46999. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47000. __decorate([
  47001. BABYLON.serialize(),
  47002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47003. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47004. __decorate([
  47005. BABYLON.serialize(),
  47006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47007. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47008. __decorate([
  47009. BABYLON.serialize(),
  47010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47011. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47012. __decorate([
  47013. BABYLON.serializeAsTexture(),
  47014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47015. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47016. __decorate([
  47017. BABYLON.serialize(),
  47018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47019. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47020. __decorate([
  47021. BABYLON.serialize(),
  47022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47023. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47024. __decorate([
  47025. BABYLON.serialize(),
  47026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47027. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47028. __decorate([
  47029. BABYLON.serialize(),
  47030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47031. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47032. __decorate([
  47033. BABYLON.serialize(),
  47034. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47035. ], PBRMaterial.prototype, "unlit", void 0);
  47036. return PBRMaterial;
  47037. }(BABYLON.PBRBaseMaterial));
  47038. BABYLON.PBRMaterial = PBRMaterial;
  47039. })(BABYLON || (BABYLON = {}));
  47040. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47041. var BABYLON;
  47042. (function (BABYLON) {
  47043. /**
  47044. * The PBR material of BJS following the metal roughness convention.
  47045. *
  47046. * This fits to the PBR convention in the GLTF definition:
  47047. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47048. */
  47049. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47050. __extends(PBRMetallicRoughnessMaterial, _super);
  47051. /**
  47052. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47053. *
  47054. * @param name The material name
  47055. * @param scene The scene the material will be use in.
  47056. */
  47057. function PBRMetallicRoughnessMaterial(name, scene) {
  47058. var _this = _super.call(this, name, scene) || this;
  47059. _this._useRoughnessFromMetallicTextureAlpha = false;
  47060. _this._useRoughnessFromMetallicTextureGreen = true;
  47061. _this._useMetallnessFromMetallicTextureBlue = true;
  47062. _this.metallic = 1.0;
  47063. _this.roughness = 1.0;
  47064. return _this;
  47065. }
  47066. /**
  47067. * Return the currrent class name of the material.
  47068. */
  47069. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47070. return "PBRMetallicRoughnessMaterial";
  47071. };
  47072. /**
  47073. * Return the active textures of the material.
  47074. */
  47075. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47076. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47077. if (this.baseTexture) {
  47078. activeTextures.push(this.baseTexture);
  47079. }
  47080. if (this.metallicRoughnessTexture) {
  47081. activeTextures.push(this.metallicRoughnessTexture);
  47082. }
  47083. return activeTextures;
  47084. };
  47085. /**
  47086. * Checks to see if a texture is used in the material.
  47087. * @param texture - Base texture to use.
  47088. * @returns - Boolean specifying if a texture is used in the material.
  47089. */
  47090. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47091. if (_super.prototype.hasTexture.call(this, texture)) {
  47092. return true;
  47093. }
  47094. if (this.baseTexture === texture) {
  47095. return true;
  47096. }
  47097. if (this.metallicRoughnessTexture === texture) {
  47098. return true;
  47099. }
  47100. return false;
  47101. };
  47102. /**
  47103. * Makes a duplicate of the current material.
  47104. * @param name - name to use for the new material.
  47105. */
  47106. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47107. var _this = this;
  47108. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47109. clone.id = name;
  47110. clone.name = name;
  47111. return clone;
  47112. };
  47113. /**
  47114. * Serialize the material to a parsable JSON object.
  47115. */
  47116. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47117. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47118. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47119. return serializationObject;
  47120. };
  47121. /**
  47122. * Parses a JSON object correponding to the serialize function.
  47123. */
  47124. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47125. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47126. };
  47127. __decorate([
  47128. BABYLON.serializeAsColor3(),
  47129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47130. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47131. __decorate([
  47132. BABYLON.serializeAsTexture(),
  47133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47134. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47135. __decorate([
  47136. BABYLON.serialize(),
  47137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47138. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47139. __decorate([
  47140. BABYLON.serialize(),
  47141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47142. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47143. __decorate([
  47144. BABYLON.serializeAsTexture(),
  47145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47146. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47147. return PBRMetallicRoughnessMaterial;
  47148. }(BABYLON.PBRBaseSimpleMaterial));
  47149. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47150. })(BABYLON || (BABYLON = {}));
  47151. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47152. var BABYLON;
  47153. (function (BABYLON) {
  47154. /**
  47155. * The PBR material of BJS following the specular glossiness convention.
  47156. *
  47157. * This fits to the PBR convention in the GLTF definition:
  47158. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47159. */
  47160. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47161. __extends(PBRSpecularGlossinessMaterial, _super);
  47162. /**
  47163. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47164. *
  47165. * @param name The material name
  47166. * @param scene The scene the material will be use in.
  47167. */
  47168. function PBRSpecularGlossinessMaterial(name, scene) {
  47169. var _this = _super.call(this, name, scene) || this;
  47170. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47171. return _this;
  47172. }
  47173. /**
  47174. * Return the currrent class name of the material.
  47175. */
  47176. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47177. return "PBRSpecularGlossinessMaterial";
  47178. };
  47179. /**
  47180. * Return the active textures of the material.
  47181. */
  47182. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47183. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47184. if (this.diffuseTexture) {
  47185. activeTextures.push(this.diffuseTexture);
  47186. }
  47187. if (this.specularGlossinessTexture) {
  47188. activeTextures.push(this.specularGlossinessTexture);
  47189. }
  47190. return activeTextures;
  47191. };
  47192. /**
  47193. * Checks to see if a texture is used in the material.
  47194. * @param texture - Base texture to use.
  47195. * @returns - Boolean specifying if a texture is used in the material.
  47196. */
  47197. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47198. if (_super.prototype.hasTexture.call(this, texture)) {
  47199. return true;
  47200. }
  47201. if (this.diffuseTexture === texture) {
  47202. return true;
  47203. }
  47204. if (this.specularGlossinessTexture === texture) {
  47205. return true;
  47206. }
  47207. return false;
  47208. };
  47209. /**
  47210. * Makes a duplicate of the current material.
  47211. * @param name - name to use for the new material.
  47212. */
  47213. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47214. var _this = this;
  47215. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47216. clone.id = name;
  47217. clone.name = name;
  47218. return clone;
  47219. };
  47220. /**
  47221. * Serialize the material to a parsable JSON object.
  47222. */
  47223. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47224. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47225. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47226. return serializationObject;
  47227. };
  47228. /**
  47229. * Parses a JSON object correponding to the serialize function.
  47230. */
  47231. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47232. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47233. };
  47234. __decorate([
  47235. BABYLON.serializeAsColor3("diffuse"),
  47236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47237. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47238. __decorate([
  47239. BABYLON.serializeAsTexture(),
  47240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47241. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47242. __decorate([
  47243. BABYLON.serializeAsColor3("specular"),
  47244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47245. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47246. __decorate([
  47247. BABYLON.serialize(),
  47248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47249. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47250. __decorate([
  47251. BABYLON.serializeAsTexture(),
  47252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47253. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47254. return PBRSpecularGlossinessMaterial;
  47255. }(BABYLON.PBRBaseSimpleMaterial));
  47256. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47257. })(BABYLON || (BABYLON = {}));
  47258. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47259. var BABYLON;
  47260. (function (BABYLON) {
  47261. BABYLON.CameraInputTypes = {};
  47262. var CameraInputsManager = /** @class */ (function () {
  47263. function CameraInputsManager(camera) {
  47264. this.attached = {};
  47265. this.camera = camera;
  47266. this.checkInputs = function () { };
  47267. }
  47268. /**
  47269. * Add an input method to a camera.
  47270. * builtin inputs example: camera.inputs.addGamepad();
  47271. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47272. * @param input camera input method
  47273. */
  47274. CameraInputsManager.prototype.add = function (input) {
  47275. var type = input.getSimpleName();
  47276. if (this.attached[type]) {
  47277. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47278. return;
  47279. }
  47280. this.attached[type] = input;
  47281. input.camera = this.camera;
  47282. //for checkInputs, we are dynamically creating a function
  47283. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47284. if (input.checkInputs) {
  47285. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47286. }
  47287. if (this.attachedElement) {
  47288. input.attachControl(this.attachedElement);
  47289. }
  47290. };
  47291. /**
  47292. * Remove a specific input method from a camera
  47293. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47294. * @param inputToRemove camera input method
  47295. */
  47296. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47297. for (var cam in this.attached) {
  47298. var input = this.attached[cam];
  47299. if (input === inputToRemove) {
  47300. input.detachControl(this.attachedElement);
  47301. input.camera = null;
  47302. delete this.attached[cam];
  47303. this.rebuildInputCheck();
  47304. }
  47305. }
  47306. };
  47307. CameraInputsManager.prototype.removeByType = function (inputType) {
  47308. for (var cam in this.attached) {
  47309. var input = this.attached[cam];
  47310. if (input.getClassName() === inputType) {
  47311. input.detachControl(this.attachedElement);
  47312. input.camera = null;
  47313. delete this.attached[cam];
  47314. this.rebuildInputCheck();
  47315. }
  47316. }
  47317. };
  47318. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47319. var current = this.checkInputs;
  47320. return function () {
  47321. current();
  47322. fn();
  47323. };
  47324. };
  47325. CameraInputsManager.prototype.attachInput = function (input) {
  47326. if (this.attachedElement) {
  47327. input.attachControl(this.attachedElement, this.noPreventDefault);
  47328. }
  47329. };
  47330. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47331. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47332. if (this.attachedElement) {
  47333. return;
  47334. }
  47335. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47336. this.attachedElement = element;
  47337. this.noPreventDefault = noPreventDefault;
  47338. for (var cam in this.attached) {
  47339. this.attached[cam].attachControl(element, noPreventDefault);
  47340. }
  47341. };
  47342. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47343. if (disconnect === void 0) { disconnect = false; }
  47344. if (this.attachedElement !== element) {
  47345. return;
  47346. }
  47347. for (var cam in this.attached) {
  47348. this.attached[cam].detachControl(element);
  47349. if (disconnect) {
  47350. this.attached[cam].camera = null;
  47351. }
  47352. }
  47353. this.attachedElement = null;
  47354. };
  47355. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47356. this.checkInputs = function () { };
  47357. for (var cam in this.attached) {
  47358. var input = this.attached[cam];
  47359. if (input.checkInputs) {
  47360. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47361. }
  47362. }
  47363. };
  47364. /**
  47365. * Remove all attached input methods from a camera
  47366. */
  47367. CameraInputsManager.prototype.clear = function () {
  47368. if (this.attachedElement) {
  47369. this.detachElement(this.attachedElement, true);
  47370. }
  47371. this.attached = {};
  47372. this.attachedElement = null;
  47373. this.checkInputs = function () { };
  47374. };
  47375. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47376. var inputs = {};
  47377. for (var cam in this.attached) {
  47378. var input = this.attached[cam];
  47379. var res = BABYLON.SerializationHelper.Serialize(input);
  47380. inputs[input.getClassName()] = res;
  47381. }
  47382. serializedCamera.inputsmgr = inputs;
  47383. };
  47384. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47385. var parsedInputs = parsedCamera.inputsmgr;
  47386. if (parsedInputs) {
  47387. this.clear();
  47388. for (var n in parsedInputs) {
  47389. var construct = BABYLON.CameraInputTypes[n];
  47390. if (construct) {
  47391. var parsedinput = parsedInputs[n];
  47392. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47393. this.add(input);
  47394. }
  47395. }
  47396. }
  47397. else {
  47398. //2016-03-08 this part is for managing backward compatibility
  47399. for (var n in this.attached) {
  47400. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47401. if (construct) {
  47402. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47403. this.remove(this.attached[n]);
  47404. this.add(input);
  47405. }
  47406. }
  47407. }
  47408. };
  47409. return CameraInputsManager;
  47410. }());
  47411. BABYLON.CameraInputsManager = CameraInputsManager;
  47412. })(BABYLON || (BABYLON = {}));
  47413. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47414. var BABYLON;
  47415. (function (BABYLON) {
  47416. var TargetCamera = /** @class */ (function (_super) {
  47417. __extends(TargetCamera, _super);
  47418. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47419. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47420. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47421. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47422. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47423. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47424. _this.speed = 2.0;
  47425. _this.noRotationConstraint = false;
  47426. _this.lockedTarget = null;
  47427. _this._currentTarget = BABYLON.Vector3.Zero();
  47428. _this._viewMatrix = BABYLON.Matrix.Zero();
  47429. _this._camMatrix = BABYLON.Matrix.Zero();
  47430. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47431. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47432. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47433. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47434. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47435. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47436. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47437. return _this;
  47438. }
  47439. TargetCamera.prototype.getFrontPosition = function (distance) {
  47440. this.getWorldMatrix();
  47441. var direction = this.getTarget().subtract(this.position);
  47442. direction.normalize();
  47443. direction.scaleInPlace(distance);
  47444. return this.globalPosition.add(direction);
  47445. };
  47446. TargetCamera.prototype._getLockedTargetPosition = function () {
  47447. if (!this.lockedTarget) {
  47448. return null;
  47449. }
  47450. if (this.lockedTarget.absolutePosition) {
  47451. this.lockedTarget.computeWorldMatrix();
  47452. }
  47453. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47454. };
  47455. TargetCamera.prototype.storeState = function () {
  47456. this._storedPosition = this.position.clone();
  47457. this._storedRotation = this.rotation.clone();
  47458. if (this.rotationQuaternion) {
  47459. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47460. }
  47461. return _super.prototype.storeState.call(this);
  47462. };
  47463. /**
  47464. * Restored camera state. You must call storeState() first
  47465. */
  47466. TargetCamera.prototype._restoreStateValues = function () {
  47467. if (!_super.prototype._restoreStateValues.call(this)) {
  47468. return false;
  47469. }
  47470. this.position = this._storedPosition.clone();
  47471. this.rotation = this._storedRotation.clone();
  47472. if (this.rotationQuaternion) {
  47473. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47474. }
  47475. this.cameraDirection.copyFromFloats(0, 0, 0);
  47476. this.cameraRotation.copyFromFloats(0, 0);
  47477. return true;
  47478. };
  47479. // Cache
  47480. TargetCamera.prototype._initCache = function () {
  47481. _super.prototype._initCache.call(this);
  47482. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47483. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47484. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47485. };
  47486. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47487. if (!ignoreParentClass) {
  47488. _super.prototype._updateCache.call(this);
  47489. }
  47490. var lockedTargetPosition = this._getLockedTargetPosition();
  47491. if (!lockedTargetPosition) {
  47492. this._cache.lockedTarget = null;
  47493. }
  47494. else {
  47495. if (!this._cache.lockedTarget) {
  47496. this._cache.lockedTarget = lockedTargetPosition.clone();
  47497. }
  47498. else {
  47499. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47500. }
  47501. }
  47502. this._cache.rotation.copyFrom(this.rotation);
  47503. if (this.rotationQuaternion)
  47504. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47505. };
  47506. // Synchronized
  47507. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47508. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47509. return false;
  47510. }
  47511. var lockedTargetPosition = this._getLockedTargetPosition();
  47512. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47513. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47514. };
  47515. // Methods
  47516. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47517. var engine = this.getEngine();
  47518. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47519. };
  47520. // Target
  47521. TargetCamera.prototype.setTarget = function (target) {
  47522. this.upVector.normalize();
  47523. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47524. this._camMatrix.invert();
  47525. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47526. var vDir = target.subtract(this.position);
  47527. if (vDir.x >= 0.0) {
  47528. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47529. }
  47530. else {
  47531. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47532. }
  47533. this.rotation.z = 0;
  47534. if (isNaN(this.rotation.x)) {
  47535. this.rotation.x = 0;
  47536. }
  47537. if (isNaN(this.rotation.y)) {
  47538. this.rotation.y = 0;
  47539. }
  47540. if (isNaN(this.rotation.z)) {
  47541. this.rotation.z = 0;
  47542. }
  47543. if (this.rotationQuaternion) {
  47544. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47545. }
  47546. };
  47547. /**
  47548. * Return the current target position of the camera. This value is expressed in local space.
  47549. */
  47550. TargetCamera.prototype.getTarget = function () {
  47551. return this._currentTarget;
  47552. };
  47553. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47554. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47555. };
  47556. TargetCamera.prototype._updatePosition = function () {
  47557. if (this.parent) {
  47558. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47559. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47560. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47561. return;
  47562. }
  47563. this.position.addInPlace(this.cameraDirection);
  47564. };
  47565. TargetCamera.prototype._checkInputs = function () {
  47566. var needToMove = this._decideIfNeedsToMove();
  47567. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47568. // Move
  47569. if (needToMove) {
  47570. this._updatePosition();
  47571. }
  47572. // Rotate
  47573. if (needToRotate) {
  47574. this.rotation.x += this.cameraRotation.x;
  47575. this.rotation.y += this.cameraRotation.y;
  47576. //rotate, if quaternion is set and rotation was used
  47577. if (this.rotationQuaternion) {
  47578. var len = this.rotation.lengthSquared();
  47579. if (len) {
  47580. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47581. }
  47582. }
  47583. if (!this.noRotationConstraint) {
  47584. var limit = (Math.PI / 2) * 0.95;
  47585. if (this.rotation.x > limit)
  47586. this.rotation.x = limit;
  47587. if (this.rotation.x < -limit)
  47588. this.rotation.x = -limit;
  47589. }
  47590. }
  47591. // Inertia
  47592. if (needToMove) {
  47593. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47594. this.cameraDirection.x = 0;
  47595. }
  47596. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47597. this.cameraDirection.y = 0;
  47598. }
  47599. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47600. this.cameraDirection.z = 0;
  47601. }
  47602. this.cameraDirection.scaleInPlace(this.inertia);
  47603. }
  47604. if (needToRotate) {
  47605. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47606. this.cameraRotation.x = 0;
  47607. }
  47608. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47609. this.cameraRotation.y = 0;
  47610. }
  47611. this.cameraRotation.scaleInPlace(this.inertia);
  47612. }
  47613. _super.prototype._checkInputs.call(this);
  47614. };
  47615. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47616. if (this.rotationQuaternion) {
  47617. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47618. }
  47619. else {
  47620. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47621. }
  47622. //update the up vector!
  47623. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47624. };
  47625. TargetCamera.prototype._getViewMatrix = function () {
  47626. if (this.lockedTarget) {
  47627. this.setTarget(this._getLockedTargetPosition());
  47628. }
  47629. // Compute
  47630. this._updateCameraRotationMatrix();
  47631. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47632. // Computing target and final matrix
  47633. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47634. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47635. return this._viewMatrix;
  47636. };
  47637. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47638. if (this.parent) {
  47639. var parentWorldMatrix = this.parent.getWorldMatrix();
  47640. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47641. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47642. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47643. this._markSyncedWithParent();
  47644. }
  47645. else {
  47646. this._globalPosition.copyFrom(this.position);
  47647. this._globalCurrentTarget.copyFrom(target);
  47648. this._globalCurrentUpVector.copyFrom(up);
  47649. }
  47650. if (this.getScene().useRightHandedSystem) {
  47651. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47652. }
  47653. else {
  47654. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47655. }
  47656. };
  47657. /**
  47658. * @override
  47659. * Override Camera.createRigCamera
  47660. */
  47661. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47662. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47663. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47664. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47665. if (!this.rotationQuaternion) {
  47666. this.rotationQuaternion = new BABYLON.Quaternion();
  47667. }
  47668. rigCamera._cameraRigParams = {};
  47669. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47670. }
  47671. return rigCamera;
  47672. }
  47673. return null;
  47674. };
  47675. /**
  47676. * @override
  47677. * Override Camera._updateRigCameras
  47678. */
  47679. TargetCamera.prototype._updateRigCameras = function () {
  47680. var camLeft = this._rigCameras[0];
  47681. var camRight = this._rigCameras[1];
  47682. switch (this.cameraRigMode) {
  47683. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47687. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47688. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47689. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47690. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47691. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47692. camLeft.setTarget(this.getTarget());
  47693. camRight.setTarget(this.getTarget());
  47694. break;
  47695. case BABYLON.Camera.RIG_MODE_VR:
  47696. if (camLeft.rotationQuaternion) {
  47697. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47698. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47699. }
  47700. else {
  47701. camLeft.rotation.copyFrom(this.rotation);
  47702. camRight.rotation.copyFrom(this.rotation);
  47703. }
  47704. camLeft.position.copyFrom(this.position);
  47705. camRight.position.copyFrom(this.position);
  47706. break;
  47707. }
  47708. _super.prototype._updateRigCameras.call(this);
  47709. };
  47710. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47711. if (!this._rigCamTransformMatrix) {
  47712. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47713. }
  47714. var target = this.getTarget();
  47715. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47716. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47717. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47718. };
  47719. TargetCamera.prototype.getClassName = function () {
  47720. return "TargetCamera";
  47721. };
  47722. __decorate([
  47723. BABYLON.serializeAsVector3()
  47724. ], TargetCamera.prototype, "rotation", void 0);
  47725. __decorate([
  47726. BABYLON.serialize()
  47727. ], TargetCamera.prototype, "speed", void 0);
  47728. __decorate([
  47729. BABYLON.serializeAsMeshReference("lockedTargetId")
  47730. ], TargetCamera.prototype, "lockedTarget", void 0);
  47731. return TargetCamera;
  47732. }(BABYLON.Camera));
  47733. BABYLON.TargetCamera = TargetCamera;
  47734. })(BABYLON || (BABYLON = {}));
  47735. //# sourceMappingURL=babylon.targetCamera.js.map
  47736. var BABYLON;
  47737. (function (BABYLON) {
  47738. var FreeCameraMouseInput = /** @class */ (function () {
  47739. function FreeCameraMouseInput(touchEnabled) {
  47740. if (touchEnabled === void 0) { touchEnabled = true; }
  47741. this.touchEnabled = touchEnabled;
  47742. this.buttons = [0, 1, 2];
  47743. this.angularSensibility = 2000.0;
  47744. this.previousPosition = null;
  47745. }
  47746. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47747. var _this = this;
  47748. var engine = this.camera.getEngine();
  47749. if (!this._pointerInput) {
  47750. this._pointerInput = function (p, s) {
  47751. var evt = p.event;
  47752. if (engine.isInVRExclusivePointerMode) {
  47753. return;
  47754. }
  47755. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47756. return;
  47757. }
  47758. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47759. return;
  47760. }
  47761. var srcElement = (evt.srcElement || evt.target);
  47762. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47763. try {
  47764. srcElement.setPointerCapture(evt.pointerId);
  47765. }
  47766. catch (e) {
  47767. //Nothing to do with the error. Execution will continue.
  47768. }
  47769. _this.previousPosition = {
  47770. x: evt.clientX,
  47771. y: evt.clientY
  47772. };
  47773. if (!noPreventDefault) {
  47774. evt.preventDefault();
  47775. element.focus();
  47776. }
  47777. }
  47778. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47779. try {
  47780. srcElement.releasePointerCapture(evt.pointerId);
  47781. }
  47782. catch (e) {
  47783. //Nothing to do with the error.
  47784. }
  47785. _this.previousPosition = null;
  47786. if (!noPreventDefault) {
  47787. evt.preventDefault();
  47788. }
  47789. }
  47790. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47791. if (!_this.previousPosition || engine.isPointerLock) {
  47792. return;
  47793. }
  47794. var offsetX = evt.clientX - _this.previousPosition.x;
  47795. if (_this.camera.getScene().useRightHandedSystem)
  47796. offsetX *= -1;
  47797. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47798. offsetX *= -1;
  47799. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47800. var offsetY = evt.clientY - _this.previousPosition.y;
  47801. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47802. _this.previousPosition = {
  47803. x: evt.clientX,
  47804. y: evt.clientY
  47805. };
  47806. if (!noPreventDefault) {
  47807. evt.preventDefault();
  47808. }
  47809. }
  47810. };
  47811. }
  47812. this._onMouseMove = function (evt) {
  47813. if (!engine.isPointerLock) {
  47814. return;
  47815. }
  47816. if (engine.isInVRExclusivePointerMode) {
  47817. return;
  47818. }
  47819. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47820. if (_this.camera.getScene().useRightHandedSystem)
  47821. offsetX *= -1;
  47822. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47823. offsetX *= -1;
  47824. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47825. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47826. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47827. _this.previousPosition = null;
  47828. if (!noPreventDefault) {
  47829. evt.preventDefault();
  47830. }
  47831. };
  47832. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47833. element.addEventListener("mousemove", this._onMouseMove, false);
  47834. };
  47835. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47836. if (this._observer && element) {
  47837. this.camera.getScene().onPointerObservable.remove(this._observer);
  47838. if (this._onMouseMove) {
  47839. element.removeEventListener("mousemove", this._onMouseMove);
  47840. }
  47841. this._observer = null;
  47842. this._onMouseMove = null;
  47843. this.previousPosition = null;
  47844. }
  47845. };
  47846. FreeCameraMouseInput.prototype.getClassName = function () {
  47847. return "FreeCameraMouseInput";
  47848. };
  47849. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47850. return "mouse";
  47851. };
  47852. __decorate([
  47853. BABYLON.serialize()
  47854. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47855. __decorate([
  47856. BABYLON.serialize()
  47857. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47858. return FreeCameraMouseInput;
  47859. }());
  47860. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47861. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47862. })(BABYLON || (BABYLON = {}));
  47863. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47864. var BABYLON;
  47865. (function (BABYLON) {
  47866. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47867. function FreeCameraKeyboardMoveInput() {
  47868. this._keys = new Array();
  47869. this.keysUp = [38];
  47870. this.keysDown = [40];
  47871. this.keysLeft = [37];
  47872. this.keysRight = [39];
  47873. }
  47874. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47875. var _this = this;
  47876. if (this._onCanvasBlurObserver) {
  47877. return;
  47878. }
  47879. this._scene = this.camera.getScene();
  47880. this._engine = this._scene.getEngine();
  47881. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47882. _this._keys = [];
  47883. });
  47884. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47885. var evt = info.event;
  47886. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47887. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47888. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47889. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47890. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47891. var index = _this._keys.indexOf(evt.keyCode);
  47892. if (index === -1) {
  47893. _this._keys.push(evt.keyCode);
  47894. }
  47895. if (!noPreventDefault) {
  47896. evt.preventDefault();
  47897. }
  47898. }
  47899. }
  47900. else {
  47901. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47902. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47903. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47904. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47905. var index = _this._keys.indexOf(evt.keyCode);
  47906. if (index >= 0) {
  47907. _this._keys.splice(index, 1);
  47908. }
  47909. if (!noPreventDefault) {
  47910. evt.preventDefault();
  47911. }
  47912. }
  47913. }
  47914. });
  47915. };
  47916. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47917. if (this._scene) {
  47918. if (this._onKeyboardObserver) {
  47919. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47920. }
  47921. if (this._onCanvasBlurObserver) {
  47922. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47923. }
  47924. this._onKeyboardObserver = null;
  47925. this._onCanvasBlurObserver = null;
  47926. }
  47927. this._keys = [];
  47928. };
  47929. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47930. if (this._onKeyboardObserver) {
  47931. var camera = this.camera;
  47932. // Keyboard
  47933. for (var index = 0; index < this._keys.length; index++) {
  47934. var keyCode = this._keys[index];
  47935. var speed = camera._computeLocalCameraSpeed();
  47936. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47937. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47938. }
  47939. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47940. camera._localDirection.copyFromFloats(0, 0, speed);
  47941. }
  47942. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47943. camera._localDirection.copyFromFloats(speed, 0, 0);
  47944. }
  47945. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47946. camera._localDirection.copyFromFloats(0, 0, -speed);
  47947. }
  47948. if (camera.getScene().useRightHandedSystem) {
  47949. camera._localDirection.z *= -1;
  47950. }
  47951. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47952. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47953. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47954. }
  47955. }
  47956. };
  47957. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47958. return "FreeCameraKeyboardMoveInput";
  47959. };
  47960. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47961. this._keys = [];
  47962. };
  47963. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47964. return "keyboard";
  47965. };
  47966. __decorate([
  47967. BABYLON.serialize()
  47968. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47969. __decorate([
  47970. BABYLON.serialize()
  47971. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47975. __decorate([
  47976. BABYLON.serialize()
  47977. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47978. return FreeCameraKeyboardMoveInput;
  47979. }());
  47980. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47981. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47982. })(BABYLON || (BABYLON = {}));
  47983. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47984. var BABYLON;
  47985. (function (BABYLON) {
  47986. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47987. __extends(FreeCameraInputsManager, _super);
  47988. function FreeCameraInputsManager(camera) {
  47989. return _super.call(this, camera) || this;
  47990. }
  47991. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47992. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47993. return this;
  47994. };
  47995. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47996. if (touchEnabled === void 0) { touchEnabled = true; }
  47997. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47998. return this;
  47999. };
  48000. FreeCameraInputsManager.prototype.addGamepad = function () {
  48001. this.add(new BABYLON.FreeCameraGamepadInput());
  48002. return this;
  48003. };
  48004. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48005. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48006. return this;
  48007. };
  48008. FreeCameraInputsManager.prototype.addTouch = function () {
  48009. this.add(new BABYLON.FreeCameraTouchInput());
  48010. return this;
  48011. };
  48012. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48013. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48014. return this;
  48015. };
  48016. return FreeCameraInputsManager;
  48017. }(BABYLON.CameraInputsManager));
  48018. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48019. })(BABYLON || (BABYLON = {}));
  48020. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48021. var BABYLON;
  48022. (function (BABYLON) {
  48023. var FreeCamera = /** @class */ (function (_super) {
  48024. __extends(FreeCamera, _super);
  48025. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48026. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48027. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48028. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48029. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48030. _this.checkCollisions = false;
  48031. _this.applyGravity = false;
  48032. _this._needMoveForGravity = false;
  48033. _this._oldPosition = BABYLON.Vector3.Zero();
  48034. _this._diffPosition = BABYLON.Vector3.Zero();
  48035. _this._newPosition = BABYLON.Vector3.Zero();
  48036. // Collisions
  48037. _this._collisionMask = -1;
  48038. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48039. if (collidedMesh === void 0) { collidedMesh = null; }
  48040. //TODO move this to the collision coordinator!
  48041. if (_this.getScene().workerCollisions)
  48042. newPosition.multiplyInPlace(_this._collider._radius);
  48043. var updatePosition = function (newPos) {
  48044. _this._newPosition.copyFrom(newPos);
  48045. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48046. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48047. _this.position.addInPlace(_this._diffPosition);
  48048. if (_this.onCollide && collidedMesh) {
  48049. _this.onCollide(collidedMesh);
  48050. }
  48051. }
  48052. };
  48053. updatePosition(newPosition);
  48054. };
  48055. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48056. _this.inputs.addKeyboard().addMouse();
  48057. return _this;
  48058. }
  48059. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48060. //-- begin properties for backward compatibility for inputs
  48061. /**
  48062. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48063. * Higher values reduce sensitivity.
  48064. */
  48065. get: function () {
  48066. var mouse = this.inputs.attached["mouse"];
  48067. if (mouse)
  48068. return mouse.angularSensibility;
  48069. return 0;
  48070. },
  48071. /**
  48072. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48073. * Higher values reduce sensitivity.
  48074. */
  48075. set: function (value) {
  48076. var mouse = this.inputs.attached["mouse"];
  48077. if (mouse)
  48078. mouse.angularSensibility = value;
  48079. },
  48080. enumerable: true,
  48081. configurable: true
  48082. });
  48083. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48084. get: function () {
  48085. var keyboard = this.inputs.attached["keyboard"];
  48086. if (keyboard)
  48087. return keyboard.keysUp;
  48088. return [];
  48089. },
  48090. set: function (value) {
  48091. var keyboard = this.inputs.attached["keyboard"];
  48092. if (keyboard)
  48093. keyboard.keysUp = value;
  48094. },
  48095. enumerable: true,
  48096. configurable: true
  48097. });
  48098. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48099. get: function () {
  48100. var keyboard = this.inputs.attached["keyboard"];
  48101. if (keyboard)
  48102. return keyboard.keysDown;
  48103. return [];
  48104. },
  48105. set: function (value) {
  48106. var keyboard = this.inputs.attached["keyboard"];
  48107. if (keyboard)
  48108. keyboard.keysDown = value;
  48109. },
  48110. enumerable: true,
  48111. configurable: true
  48112. });
  48113. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48114. get: function () {
  48115. var keyboard = this.inputs.attached["keyboard"];
  48116. if (keyboard)
  48117. return keyboard.keysLeft;
  48118. return [];
  48119. },
  48120. set: function (value) {
  48121. var keyboard = this.inputs.attached["keyboard"];
  48122. if (keyboard)
  48123. keyboard.keysLeft = value;
  48124. },
  48125. enumerable: true,
  48126. configurable: true
  48127. });
  48128. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48129. get: function () {
  48130. var keyboard = this.inputs.attached["keyboard"];
  48131. if (keyboard)
  48132. return keyboard.keysRight;
  48133. return [];
  48134. },
  48135. set: function (value) {
  48136. var keyboard = this.inputs.attached["keyboard"];
  48137. if (keyboard)
  48138. keyboard.keysRight = value;
  48139. },
  48140. enumerable: true,
  48141. configurable: true
  48142. });
  48143. // Controls
  48144. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48145. this.inputs.attachElement(element, noPreventDefault);
  48146. };
  48147. FreeCamera.prototype.detachControl = function (element) {
  48148. this.inputs.detachElement(element);
  48149. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48150. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48151. };
  48152. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48153. get: function () {
  48154. return this._collisionMask;
  48155. },
  48156. set: function (mask) {
  48157. this._collisionMask = !isNaN(mask) ? mask : -1;
  48158. },
  48159. enumerable: true,
  48160. configurable: true
  48161. });
  48162. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48163. var globalPosition;
  48164. if (this.parent) {
  48165. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48166. }
  48167. else {
  48168. globalPosition = this.position;
  48169. }
  48170. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48171. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48172. if (!this._collider) {
  48173. this._collider = new BABYLON.Collider();
  48174. }
  48175. this._collider._radius = this.ellipsoid;
  48176. this._collider.collisionMask = this._collisionMask;
  48177. //no need for clone, as long as gravity is not on.
  48178. var actualDisplacement = displacement;
  48179. //add gravity to the direction to prevent the dual-collision checking
  48180. if (this.applyGravity) {
  48181. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48182. actualDisplacement = displacement.add(this.getScene().gravity);
  48183. }
  48184. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48185. };
  48186. FreeCamera.prototype._checkInputs = function () {
  48187. if (!this._localDirection) {
  48188. this._localDirection = BABYLON.Vector3.Zero();
  48189. this._transformedDirection = BABYLON.Vector3.Zero();
  48190. }
  48191. this.inputs.checkInputs();
  48192. _super.prototype._checkInputs.call(this);
  48193. };
  48194. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48195. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48196. };
  48197. FreeCamera.prototype._updatePosition = function () {
  48198. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48199. this._collideWithWorld(this.cameraDirection);
  48200. }
  48201. else {
  48202. _super.prototype._updatePosition.call(this);
  48203. }
  48204. };
  48205. FreeCamera.prototype.dispose = function () {
  48206. this.inputs.clear();
  48207. _super.prototype.dispose.call(this);
  48208. };
  48209. FreeCamera.prototype.getClassName = function () {
  48210. return "FreeCamera";
  48211. };
  48212. __decorate([
  48213. BABYLON.serializeAsVector3()
  48214. ], FreeCamera.prototype, "ellipsoid", void 0);
  48215. __decorate([
  48216. BABYLON.serializeAsVector3()
  48217. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48218. __decorate([
  48219. BABYLON.serialize()
  48220. ], FreeCamera.prototype, "checkCollisions", void 0);
  48221. __decorate([
  48222. BABYLON.serialize()
  48223. ], FreeCamera.prototype, "applyGravity", void 0);
  48224. return FreeCamera;
  48225. }(BABYLON.TargetCamera));
  48226. BABYLON.FreeCamera = FreeCamera;
  48227. })(BABYLON || (BABYLON = {}));
  48228. //# sourceMappingURL=babylon.freeCamera.js.map
  48229. var BABYLON;
  48230. (function (BABYLON) {
  48231. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48232. function ArcRotateCameraKeyboardMoveInput() {
  48233. this._keys = new Array();
  48234. this.keysUp = [38];
  48235. this.keysDown = [40];
  48236. this.keysLeft = [37];
  48237. this.keysRight = [39];
  48238. this.keysReset = [220];
  48239. this.panningSensibility = 50.0;
  48240. this.zoomingSensibility = 25.0;
  48241. this.useAltToZoom = true;
  48242. }
  48243. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48244. var _this = this;
  48245. if (this._onCanvasBlurObserver) {
  48246. return;
  48247. }
  48248. this._scene = this.camera.getScene();
  48249. this._engine = this._scene.getEngine();
  48250. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48251. _this._keys = [];
  48252. });
  48253. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48254. var evt = info.event;
  48255. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48256. _this._ctrlPressed = evt.ctrlKey;
  48257. _this._altPressed = evt.altKey;
  48258. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48259. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48260. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48261. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48262. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48263. var index = _this._keys.indexOf(evt.keyCode);
  48264. if (index === -1) {
  48265. _this._keys.push(evt.keyCode);
  48266. }
  48267. if (evt.preventDefault) {
  48268. if (!noPreventDefault) {
  48269. evt.preventDefault();
  48270. }
  48271. }
  48272. }
  48273. }
  48274. else {
  48275. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48276. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48277. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48278. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48279. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48280. var index = _this._keys.indexOf(evt.keyCode);
  48281. if (index >= 0) {
  48282. _this._keys.splice(index, 1);
  48283. }
  48284. if (evt.preventDefault) {
  48285. if (!noPreventDefault) {
  48286. evt.preventDefault();
  48287. }
  48288. }
  48289. }
  48290. }
  48291. });
  48292. };
  48293. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48294. if (this._scene) {
  48295. if (this._onKeyboardObserver) {
  48296. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48297. }
  48298. if (this._onCanvasBlurObserver) {
  48299. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48300. }
  48301. this._onKeyboardObserver = null;
  48302. this._onCanvasBlurObserver = null;
  48303. }
  48304. this._keys = [];
  48305. };
  48306. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48307. if (this._onKeyboardObserver) {
  48308. var camera = this.camera;
  48309. for (var index = 0; index < this._keys.length; index++) {
  48310. var keyCode = this._keys[index];
  48311. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48312. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48313. camera.inertialPanningX -= 1 / this.panningSensibility;
  48314. }
  48315. else {
  48316. camera.inertialAlphaOffset -= 0.01;
  48317. }
  48318. }
  48319. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48320. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48321. camera.inertialPanningY += 1 / this.panningSensibility;
  48322. }
  48323. else if (this._altPressed && this.useAltToZoom) {
  48324. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48325. }
  48326. else {
  48327. camera.inertialBetaOffset -= 0.01;
  48328. }
  48329. }
  48330. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48331. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48332. camera.inertialPanningX += 1 / this.panningSensibility;
  48333. }
  48334. else {
  48335. camera.inertialAlphaOffset += 0.01;
  48336. }
  48337. }
  48338. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48339. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48340. camera.inertialPanningY -= 1 / this.panningSensibility;
  48341. }
  48342. else if (this._altPressed && this.useAltToZoom) {
  48343. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48344. }
  48345. else {
  48346. camera.inertialBetaOffset += 0.01;
  48347. }
  48348. }
  48349. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48350. camera.restoreState();
  48351. }
  48352. }
  48353. }
  48354. };
  48355. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48356. return "ArcRotateCameraKeyboardMoveInput";
  48357. };
  48358. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48359. return "keyboard";
  48360. };
  48361. __decorate([
  48362. BABYLON.serialize()
  48363. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48364. __decorate([
  48365. BABYLON.serialize()
  48366. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48367. __decorate([
  48368. BABYLON.serialize()
  48369. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48370. __decorate([
  48371. BABYLON.serialize()
  48372. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48373. __decorate([
  48374. BABYLON.serialize()
  48375. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48376. __decorate([
  48377. BABYLON.serialize()
  48378. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48379. __decorate([
  48380. BABYLON.serialize()
  48381. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48382. __decorate([
  48383. BABYLON.serialize()
  48384. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48385. return ArcRotateCameraKeyboardMoveInput;
  48386. }());
  48387. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48388. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48389. })(BABYLON || (BABYLON = {}));
  48390. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48391. var BABYLON;
  48392. (function (BABYLON) {
  48393. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48394. function ArcRotateCameraMouseWheelInput() {
  48395. this.wheelPrecision = 3.0;
  48396. /**
  48397. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48398. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48399. */
  48400. this.wheelDeltaPercentage = 0;
  48401. }
  48402. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48403. var _this = this;
  48404. this._wheel = function (p, s) {
  48405. //sanity check - this should be a PointerWheel event.
  48406. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48407. return;
  48408. var event = p.event;
  48409. var delta = 0;
  48410. if (event.wheelDelta) {
  48411. if (_this.wheelDeltaPercentage) {
  48412. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48413. if (event.wheelDelta > 0) {
  48414. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48415. }
  48416. else {
  48417. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48418. }
  48419. }
  48420. else {
  48421. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48422. }
  48423. }
  48424. else if (event.detail) {
  48425. delta = -event.detail / _this.wheelPrecision;
  48426. }
  48427. if (delta)
  48428. _this.camera.inertialRadiusOffset += delta;
  48429. if (event.preventDefault) {
  48430. if (!noPreventDefault) {
  48431. event.preventDefault();
  48432. }
  48433. }
  48434. };
  48435. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48436. };
  48437. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48438. if (this._observer && element) {
  48439. this.camera.getScene().onPointerObservable.remove(this._observer);
  48440. this._observer = null;
  48441. this._wheel = null;
  48442. }
  48443. };
  48444. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48445. return "ArcRotateCameraMouseWheelInput";
  48446. };
  48447. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48448. return "mousewheel";
  48449. };
  48450. __decorate([
  48451. BABYLON.serialize()
  48452. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48453. __decorate([
  48454. BABYLON.serialize()
  48455. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48456. return ArcRotateCameraMouseWheelInput;
  48457. }());
  48458. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48459. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48460. })(BABYLON || (BABYLON = {}));
  48461. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48462. var BABYLON;
  48463. (function (BABYLON) {
  48464. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48465. function ArcRotateCameraPointersInput() {
  48466. this.buttons = [0, 1, 2];
  48467. this.angularSensibilityX = 1000.0;
  48468. this.angularSensibilityY = 1000.0;
  48469. this.pinchPrecision = 12.0;
  48470. /**
  48471. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48472. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48473. */
  48474. this.pinchDeltaPercentage = 0;
  48475. this.panningSensibility = 1000.0;
  48476. this.multiTouchPanning = true;
  48477. this.multiTouchPanAndZoom = true;
  48478. this._isPanClick = false;
  48479. this.pinchInwards = true;
  48480. }
  48481. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48482. var _this = this;
  48483. var engine = this.camera.getEngine();
  48484. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48485. var pointA = null;
  48486. var pointB = null;
  48487. var previousPinchSquaredDistance = 0;
  48488. var initialDistance = 0;
  48489. var twoFingerActivityCount = 0;
  48490. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48491. this._pointerInput = function (p, s) {
  48492. var evt = p.event;
  48493. var isTouch = p.event.pointerType === "touch";
  48494. if (engine.isInVRExclusivePointerMode) {
  48495. return;
  48496. }
  48497. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48498. return;
  48499. }
  48500. var srcElement = (evt.srcElement || evt.target);
  48501. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48502. try {
  48503. srcElement.setPointerCapture(evt.pointerId);
  48504. }
  48505. catch (e) {
  48506. //Nothing to do with the error. Execution will continue.
  48507. }
  48508. // Manage panning with pan button click
  48509. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48510. // manage pointers
  48511. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48512. if (pointA === null) {
  48513. pointA = cacheSoloPointer;
  48514. }
  48515. else if (pointB === null) {
  48516. pointB = cacheSoloPointer;
  48517. }
  48518. if (!noPreventDefault) {
  48519. evt.preventDefault();
  48520. element.focus();
  48521. }
  48522. }
  48523. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48524. _this.camera.restoreState();
  48525. }
  48526. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48527. try {
  48528. srcElement.releasePointerCapture(evt.pointerId);
  48529. }
  48530. catch (e) {
  48531. //Nothing to do with the error.
  48532. }
  48533. cacheSoloPointer = null;
  48534. previousPinchSquaredDistance = 0;
  48535. previousMultiTouchPanPosition.isPaning = false;
  48536. previousMultiTouchPanPosition.isPinching = false;
  48537. twoFingerActivityCount = 0;
  48538. initialDistance = 0;
  48539. if (!isTouch) {
  48540. pointB = null; // Mouse and pen are mono pointer
  48541. }
  48542. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48543. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48544. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48545. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48546. if (engine._badOS) {
  48547. pointA = pointB = null;
  48548. }
  48549. else {
  48550. //only remove the impacted pointer in case of multitouch allowing on most
  48551. //platforms switching from rotate to zoom and pan seamlessly.
  48552. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48553. pointA = pointB;
  48554. pointB = null;
  48555. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48556. }
  48557. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48558. pointB = null;
  48559. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48560. }
  48561. else {
  48562. pointA = pointB = null;
  48563. }
  48564. }
  48565. if (!noPreventDefault) {
  48566. evt.preventDefault();
  48567. }
  48568. }
  48569. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48570. if (!noPreventDefault) {
  48571. evt.preventDefault();
  48572. }
  48573. // One button down
  48574. if (pointA && pointB === null && cacheSoloPointer) {
  48575. if (_this.panningSensibility !== 0 &&
  48576. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48577. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48578. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48579. }
  48580. else {
  48581. var offsetX = evt.clientX - cacheSoloPointer.x;
  48582. var offsetY = evt.clientY - cacheSoloPointer.y;
  48583. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48584. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48585. }
  48586. cacheSoloPointer.x = evt.clientX;
  48587. cacheSoloPointer.y = evt.clientY;
  48588. }
  48589. // Two buttons down: pinch/pan
  48590. else if (pointA && pointB) {
  48591. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48592. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48593. ed.x = evt.clientX;
  48594. ed.y = evt.clientY;
  48595. var direction = _this.pinchInwards ? 1 : -1;
  48596. var distX = pointA.x - pointB.x;
  48597. var distY = pointA.y - pointB.y;
  48598. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48599. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48600. if (previousPinchSquaredDistance === 0) {
  48601. initialDistance = pinchDistance;
  48602. previousPinchSquaredDistance = pinchSquaredDistance;
  48603. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48604. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48605. return;
  48606. }
  48607. if (_this.multiTouchPanAndZoom) {
  48608. if (_this.pinchDeltaPercentage) {
  48609. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48610. }
  48611. else {
  48612. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48613. (_this.pinchPrecision *
  48614. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48615. direction);
  48616. }
  48617. if (_this.panningSensibility !== 0) {
  48618. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48619. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48620. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48621. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48622. previousMultiTouchPanPosition.x = pointersCenterX;
  48623. previousMultiTouchPanPosition.y = pointersCenterY;
  48624. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48625. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48626. }
  48627. }
  48628. else {
  48629. twoFingerActivityCount++;
  48630. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48631. if (_this.pinchDeltaPercentage) {
  48632. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48633. }
  48634. else {
  48635. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48636. (_this.pinchPrecision *
  48637. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48638. direction);
  48639. }
  48640. previousMultiTouchPanPosition.isPaning = false;
  48641. previousMultiTouchPanPosition.isPinching = true;
  48642. }
  48643. else {
  48644. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48645. if (!previousMultiTouchPanPosition.isPaning) {
  48646. previousMultiTouchPanPosition.isPaning = true;
  48647. previousMultiTouchPanPosition.isPinching = false;
  48648. previousMultiTouchPanPosition.x = ed.x;
  48649. previousMultiTouchPanPosition.y = ed.y;
  48650. return;
  48651. }
  48652. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48653. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48654. }
  48655. }
  48656. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48657. previousMultiTouchPanPosition.x = ed.x;
  48658. previousMultiTouchPanPosition.y = ed.y;
  48659. }
  48660. }
  48661. previousPinchSquaredDistance = pinchSquaredDistance;
  48662. }
  48663. }
  48664. };
  48665. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48666. this._onContextMenu = function (evt) {
  48667. evt.preventDefault();
  48668. };
  48669. if (!this.camera._useCtrlForPanning) {
  48670. element.addEventListener("contextmenu", this._onContextMenu, false);
  48671. }
  48672. this._onLostFocus = function () {
  48673. //this._keys = [];
  48674. pointA = pointB = null;
  48675. previousPinchSquaredDistance = 0;
  48676. previousMultiTouchPanPosition.isPaning = false;
  48677. previousMultiTouchPanPosition.isPinching = false;
  48678. twoFingerActivityCount = 0;
  48679. cacheSoloPointer = null;
  48680. initialDistance = 0;
  48681. };
  48682. this._onMouseMove = function (evt) {
  48683. if (!engine.isPointerLock) {
  48684. return;
  48685. }
  48686. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48687. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48688. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48689. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48690. if (!noPreventDefault) {
  48691. evt.preventDefault();
  48692. }
  48693. };
  48694. this._onGestureStart = function (e) {
  48695. if (window.MSGesture === undefined) {
  48696. return;
  48697. }
  48698. if (!_this._MSGestureHandler) {
  48699. _this._MSGestureHandler = new MSGesture();
  48700. _this._MSGestureHandler.target = element;
  48701. }
  48702. _this._MSGestureHandler.addPointer(e.pointerId);
  48703. };
  48704. this._onGesture = function (e) {
  48705. _this.camera.radius *= e.scale;
  48706. if (e.preventDefault) {
  48707. if (!noPreventDefault) {
  48708. e.stopPropagation();
  48709. e.preventDefault();
  48710. }
  48711. }
  48712. };
  48713. element.addEventListener("mousemove", this._onMouseMove, false);
  48714. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48715. element.addEventListener("MSGestureChange", this._onGesture, false);
  48716. BABYLON.Tools.RegisterTopRootEvents([
  48717. { name: "blur", handler: this._onLostFocus }
  48718. ]);
  48719. };
  48720. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48721. if (this._onLostFocus) {
  48722. BABYLON.Tools.UnregisterTopRootEvents([
  48723. { name: "blur", handler: this._onLostFocus }
  48724. ]);
  48725. }
  48726. if (element && this._observer) {
  48727. this.camera.getScene().onPointerObservable.remove(this._observer);
  48728. this._observer = null;
  48729. if (this._onContextMenu) {
  48730. element.removeEventListener("contextmenu", this._onContextMenu);
  48731. }
  48732. if (this._onMouseMove) {
  48733. element.removeEventListener("mousemove", this._onMouseMove);
  48734. }
  48735. if (this._onGestureStart) {
  48736. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48737. }
  48738. if (this._onGesture) {
  48739. element.removeEventListener("MSGestureChange", this._onGesture);
  48740. }
  48741. this._isPanClick = false;
  48742. this.pinchInwards = true;
  48743. this._onMouseMove = null;
  48744. this._onGestureStart = null;
  48745. this._onGesture = null;
  48746. this._MSGestureHandler = null;
  48747. this._onLostFocus = null;
  48748. this._onContextMenu = null;
  48749. }
  48750. };
  48751. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48752. return "ArcRotateCameraPointersInput";
  48753. };
  48754. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48755. return "pointers";
  48756. };
  48757. __decorate([
  48758. BABYLON.serialize()
  48759. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48760. __decorate([
  48761. BABYLON.serialize()
  48762. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48763. __decorate([
  48764. BABYLON.serialize()
  48765. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48766. __decorate([
  48767. BABYLON.serialize()
  48768. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48769. __decorate([
  48770. BABYLON.serialize()
  48771. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48772. __decorate([
  48773. BABYLON.serialize()
  48774. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48775. __decorate([
  48776. BABYLON.serialize()
  48777. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48778. __decorate([
  48779. BABYLON.serialize()
  48780. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48781. return ArcRotateCameraPointersInput;
  48782. }());
  48783. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48784. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48785. })(BABYLON || (BABYLON = {}));
  48786. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48787. var BABYLON;
  48788. (function (BABYLON) {
  48789. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48790. __extends(ArcRotateCameraInputsManager, _super);
  48791. function ArcRotateCameraInputsManager(camera) {
  48792. return _super.call(this, camera) || this;
  48793. }
  48794. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48795. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48796. return this;
  48797. };
  48798. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48799. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48800. return this;
  48801. };
  48802. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48803. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48804. return this;
  48805. };
  48806. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48807. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48808. return this;
  48809. };
  48810. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48811. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48812. return this;
  48813. };
  48814. return ArcRotateCameraInputsManager;
  48815. }(BABYLON.CameraInputsManager));
  48816. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48817. })(BABYLON || (BABYLON = {}));
  48818. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48819. var BABYLON;
  48820. (function (BABYLON) {
  48821. var ArcRotateCamera = /** @class */ (function (_super) {
  48822. __extends(ArcRotateCamera, _super);
  48823. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48824. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48825. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48826. _this.inertialAlphaOffset = 0;
  48827. _this.inertialBetaOffset = 0;
  48828. _this.inertialRadiusOffset = 0;
  48829. _this.lowerAlphaLimit = null;
  48830. _this.upperAlphaLimit = null;
  48831. _this.lowerBetaLimit = 0.01;
  48832. _this.upperBetaLimit = Math.PI;
  48833. _this.lowerRadiusLimit = null;
  48834. _this.upperRadiusLimit = null;
  48835. _this.inertialPanningX = 0;
  48836. _this.inertialPanningY = 0;
  48837. _this.pinchToPanMaxDistance = 20;
  48838. _this.panningDistanceLimit = null;
  48839. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48840. _this.panningInertia = 0.9;
  48841. //-- end properties for backward compatibility for inputs
  48842. _this.zoomOnFactor = 1;
  48843. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48844. _this.allowUpsideDown = true;
  48845. _this._viewMatrix = new BABYLON.Matrix();
  48846. // Panning
  48847. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48848. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48849. _this.checkCollisions = false;
  48850. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48851. _this._previousPosition = BABYLON.Vector3.Zero();
  48852. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48853. _this._newPosition = BABYLON.Vector3.Zero();
  48854. _this._computationVector = BABYLON.Vector3.Zero();
  48855. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48856. if (collidedMesh === void 0) { collidedMesh = null; }
  48857. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48858. newPosition.multiplyInPlace(_this._collider._radius);
  48859. }
  48860. if (!collidedMesh) {
  48861. _this._previousPosition.copyFrom(_this.position);
  48862. }
  48863. else {
  48864. _this.setPosition(newPosition);
  48865. if (_this.onCollide) {
  48866. _this.onCollide(collidedMesh);
  48867. }
  48868. }
  48869. // Recompute because of constraints
  48870. var cosa = Math.cos(_this.alpha);
  48871. var sina = Math.sin(_this.alpha);
  48872. var cosb = Math.cos(_this.beta);
  48873. var sinb = Math.sin(_this.beta);
  48874. if (sinb === 0) {
  48875. sinb = 0.0001;
  48876. }
  48877. var target = _this._getTargetPosition();
  48878. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48879. target.addToRef(_this._computationVector, _this._newPosition);
  48880. _this.position.copyFrom(_this._newPosition);
  48881. var up = _this.upVector;
  48882. if (_this.allowUpsideDown && _this.beta < 0) {
  48883. up = up.clone();
  48884. up = up.negate();
  48885. }
  48886. _this._computeViewMatrix(_this.position, target, up);
  48887. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48888. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48889. _this._collisionTriggered = false;
  48890. };
  48891. _this._target = BABYLON.Vector3.Zero();
  48892. if (target) {
  48893. _this.setTarget(target);
  48894. }
  48895. _this.alpha = alpha;
  48896. _this.beta = beta;
  48897. _this.radius = radius;
  48898. _this.getViewMatrix();
  48899. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48900. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48901. return _this;
  48902. }
  48903. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48904. get: function () {
  48905. return this._target;
  48906. },
  48907. set: function (value) {
  48908. this.setTarget(value);
  48909. },
  48910. enumerable: true,
  48911. configurable: true
  48912. });
  48913. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48914. //-- begin properties for backward compatibility for inputs
  48915. get: function () {
  48916. var pointers = this.inputs.attached["pointers"];
  48917. if (pointers)
  48918. return pointers.angularSensibilityX;
  48919. return 0;
  48920. },
  48921. set: function (value) {
  48922. var pointers = this.inputs.attached["pointers"];
  48923. if (pointers) {
  48924. pointers.angularSensibilityX = value;
  48925. }
  48926. },
  48927. enumerable: true,
  48928. configurable: true
  48929. });
  48930. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48931. get: function () {
  48932. var pointers = this.inputs.attached["pointers"];
  48933. if (pointers)
  48934. return pointers.angularSensibilityY;
  48935. return 0;
  48936. },
  48937. set: function (value) {
  48938. var pointers = this.inputs.attached["pointers"];
  48939. if (pointers) {
  48940. pointers.angularSensibilityY = value;
  48941. }
  48942. },
  48943. enumerable: true,
  48944. configurable: true
  48945. });
  48946. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48947. get: function () {
  48948. var pointers = this.inputs.attached["pointers"];
  48949. if (pointers)
  48950. return pointers.pinchPrecision;
  48951. return 0;
  48952. },
  48953. set: function (value) {
  48954. var pointers = this.inputs.attached["pointers"];
  48955. if (pointers) {
  48956. pointers.pinchPrecision = value;
  48957. }
  48958. },
  48959. enumerable: true,
  48960. configurable: true
  48961. });
  48962. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48963. get: function () {
  48964. var pointers = this.inputs.attached["pointers"];
  48965. if (pointers)
  48966. return pointers.pinchDeltaPercentage;
  48967. return 0;
  48968. },
  48969. set: function (value) {
  48970. var pointers = this.inputs.attached["pointers"];
  48971. if (pointers) {
  48972. pointers.pinchDeltaPercentage = value;
  48973. }
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48979. get: function () {
  48980. var pointers = this.inputs.attached["pointers"];
  48981. if (pointers)
  48982. return pointers.panningSensibility;
  48983. return 0;
  48984. },
  48985. set: function (value) {
  48986. var pointers = this.inputs.attached["pointers"];
  48987. if (pointers) {
  48988. pointers.panningSensibility = value;
  48989. }
  48990. },
  48991. enumerable: true,
  48992. configurable: true
  48993. });
  48994. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48995. get: function () {
  48996. var keyboard = this.inputs.attached["keyboard"];
  48997. if (keyboard)
  48998. return keyboard.keysUp;
  48999. return [];
  49000. },
  49001. set: function (value) {
  49002. var keyboard = this.inputs.attached["keyboard"];
  49003. if (keyboard)
  49004. keyboard.keysUp = value;
  49005. },
  49006. enumerable: true,
  49007. configurable: true
  49008. });
  49009. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49010. get: function () {
  49011. var keyboard = this.inputs.attached["keyboard"];
  49012. if (keyboard)
  49013. return keyboard.keysDown;
  49014. return [];
  49015. },
  49016. set: function (value) {
  49017. var keyboard = this.inputs.attached["keyboard"];
  49018. if (keyboard)
  49019. keyboard.keysDown = value;
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49025. get: function () {
  49026. var keyboard = this.inputs.attached["keyboard"];
  49027. if (keyboard)
  49028. return keyboard.keysLeft;
  49029. return [];
  49030. },
  49031. set: function (value) {
  49032. var keyboard = this.inputs.attached["keyboard"];
  49033. if (keyboard)
  49034. keyboard.keysLeft = value;
  49035. },
  49036. enumerable: true,
  49037. configurable: true
  49038. });
  49039. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49040. get: function () {
  49041. var keyboard = this.inputs.attached["keyboard"];
  49042. if (keyboard)
  49043. return keyboard.keysRight;
  49044. return [];
  49045. },
  49046. set: function (value) {
  49047. var keyboard = this.inputs.attached["keyboard"];
  49048. if (keyboard)
  49049. keyboard.keysRight = value;
  49050. },
  49051. enumerable: true,
  49052. configurable: true
  49053. });
  49054. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49055. get: function () {
  49056. var mousewheel = this.inputs.attached["mousewheel"];
  49057. if (mousewheel)
  49058. return mousewheel.wheelPrecision;
  49059. return 0;
  49060. },
  49061. set: function (value) {
  49062. var mousewheel = this.inputs.attached["mousewheel"];
  49063. if (mousewheel)
  49064. mousewheel.wheelPrecision = value;
  49065. },
  49066. enumerable: true,
  49067. configurable: true
  49068. });
  49069. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49070. get: function () {
  49071. var mousewheel = this.inputs.attached["mousewheel"];
  49072. if (mousewheel)
  49073. return mousewheel.wheelDeltaPercentage;
  49074. return 0;
  49075. },
  49076. set: function (value) {
  49077. var mousewheel = this.inputs.attached["mousewheel"];
  49078. if (mousewheel)
  49079. mousewheel.wheelDeltaPercentage = value;
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49085. get: function () {
  49086. return this._bouncingBehavior;
  49087. },
  49088. enumerable: true,
  49089. configurable: true
  49090. });
  49091. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49092. get: function () {
  49093. return this._bouncingBehavior != null;
  49094. },
  49095. set: function (value) {
  49096. if (value === this.useBouncingBehavior) {
  49097. return;
  49098. }
  49099. if (value) {
  49100. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49101. this.addBehavior(this._bouncingBehavior);
  49102. }
  49103. else if (this._bouncingBehavior) {
  49104. this.removeBehavior(this._bouncingBehavior);
  49105. this._bouncingBehavior = null;
  49106. }
  49107. },
  49108. enumerable: true,
  49109. configurable: true
  49110. });
  49111. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49112. get: function () {
  49113. return this._framingBehavior;
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49119. get: function () {
  49120. return this._framingBehavior != null;
  49121. },
  49122. set: function (value) {
  49123. if (value === this.useFramingBehavior) {
  49124. return;
  49125. }
  49126. if (value) {
  49127. this._framingBehavior = new BABYLON.FramingBehavior();
  49128. this.addBehavior(this._framingBehavior);
  49129. }
  49130. else if (this._framingBehavior) {
  49131. this.removeBehavior(this._framingBehavior);
  49132. this._framingBehavior = null;
  49133. }
  49134. },
  49135. enumerable: true,
  49136. configurable: true
  49137. });
  49138. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49139. get: function () {
  49140. return this._autoRotationBehavior;
  49141. },
  49142. enumerable: true,
  49143. configurable: true
  49144. });
  49145. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49146. get: function () {
  49147. return this._autoRotationBehavior != null;
  49148. },
  49149. set: function (value) {
  49150. if (value === this.useAutoRotationBehavior) {
  49151. return;
  49152. }
  49153. if (value) {
  49154. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49155. this.addBehavior(this._autoRotationBehavior);
  49156. }
  49157. else if (this._autoRotationBehavior) {
  49158. this.removeBehavior(this._autoRotationBehavior);
  49159. this._autoRotationBehavior = null;
  49160. }
  49161. },
  49162. enumerable: true,
  49163. configurable: true
  49164. });
  49165. // Cache
  49166. ArcRotateCamera.prototype._initCache = function () {
  49167. _super.prototype._initCache.call(this);
  49168. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49169. this._cache.alpha = undefined;
  49170. this._cache.beta = undefined;
  49171. this._cache.radius = undefined;
  49172. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49173. };
  49174. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49175. if (!ignoreParentClass) {
  49176. _super.prototype._updateCache.call(this);
  49177. }
  49178. this._cache._target.copyFrom(this._getTargetPosition());
  49179. this._cache.alpha = this.alpha;
  49180. this._cache.beta = this.beta;
  49181. this._cache.radius = this.radius;
  49182. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49183. };
  49184. ArcRotateCamera.prototype._getTargetPosition = function () {
  49185. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49186. var pos = this._targetHost.getAbsolutePosition();
  49187. if (this._targetBoundingCenter) {
  49188. pos.addToRef(this._targetBoundingCenter, this._target);
  49189. }
  49190. else {
  49191. this._target.copyFrom(pos);
  49192. }
  49193. }
  49194. var lockedTargetPosition = this._getLockedTargetPosition();
  49195. if (lockedTargetPosition) {
  49196. return lockedTargetPosition;
  49197. }
  49198. return this._target;
  49199. };
  49200. ArcRotateCamera.prototype.storeState = function () {
  49201. this._storedAlpha = this.alpha;
  49202. this._storedBeta = this.beta;
  49203. this._storedRadius = this.radius;
  49204. this._storedTarget = this._getTargetPosition().clone();
  49205. return _super.prototype.storeState.call(this);
  49206. };
  49207. /**
  49208. * Restored camera state. You must call storeState() first
  49209. */
  49210. ArcRotateCamera.prototype._restoreStateValues = function () {
  49211. if (!_super.prototype._restoreStateValues.call(this)) {
  49212. return false;
  49213. }
  49214. this.alpha = this._storedAlpha;
  49215. this.beta = this._storedBeta;
  49216. this.radius = this._storedRadius;
  49217. this.setTarget(this._storedTarget.clone());
  49218. this.inertialAlphaOffset = 0;
  49219. this.inertialBetaOffset = 0;
  49220. this.inertialRadiusOffset = 0;
  49221. this.inertialPanningX = 0;
  49222. this.inertialPanningY = 0;
  49223. return true;
  49224. };
  49225. // Synchronized
  49226. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49227. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49228. return false;
  49229. return this._cache._target.equals(this._getTargetPosition())
  49230. && this._cache.alpha === this.alpha
  49231. && this._cache.beta === this.beta
  49232. && this._cache.radius === this.radius
  49233. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49234. };
  49235. // Methods
  49236. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49237. var _this = this;
  49238. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49239. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49240. this._useCtrlForPanning = useCtrlForPanning;
  49241. this._panningMouseButton = panningMouseButton;
  49242. this.inputs.attachElement(element, noPreventDefault);
  49243. this._reset = function () {
  49244. _this.inertialAlphaOffset = 0;
  49245. _this.inertialBetaOffset = 0;
  49246. _this.inertialRadiusOffset = 0;
  49247. _this.inertialPanningX = 0;
  49248. _this.inertialPanningY = 0;
  49249. };
  49250. };
  49251. ArcRotateCamera.prototype.detachControl = function (element) {
  49252. this.inputs.detachElement(element);
  49253. if (this._reset) {
  49254. this._reset();
  49255. }
  49256. };
  49257. ArcRotateCamera.prototype._checkInputs = function () {
  49258. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49259. if (this._collisionTriggered) {
  49260. return;
  49261. }
  49262. this.inputs.checkInputs();
  49263. // Inertia
  49264. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49265. var inertialAlphaOffset = this.inertialAlphaOffset;
  49266. if (this.beta <= 0)
  49267. inertialAlphaOffset *= -1;
  49268. if (this.getScene().useRightHandedSystem)
  49269. inertialAlphaOffset *= -1;
  49270. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49271. inertialAlphaOffset *= -1;
  49272. this.alpha += inertialAlphaOffset;
  49273. this.beta += this.inertialBetaOffset;
  49274. this.radius -= this.inertialRadiusOffset;
  49275. this.inertialAlphaOffset *= this.inertia;
  49276. this.inertialBetaOffset *= this.inertia;
  49277. this.inertialRadiusOffset *= this.inertia;
  49278. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49279. this.inertialAlphaOffset = 0;
  49280. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49281. this.inertialBetaOffset = 0;
  49282. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49283. this.inertialRadiusOffset = 0;
  49284. }
  49285. // Panning inertia
  49286. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49287. if (!this._localDirection) {
  49288. this._localDirection = BABYLON.Vector3.Zero();
  49289. this._transformedDirection = BABYLON.Vector3.Zero();
  49290. }
  49291. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49292. this._localDirection.multiplyInPlace(this.panningAxis);
  49293. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49294. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49295. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49296. if (!this.panningAxis.y) {
  49297. this._transformedDirection.y = 0;
  49298. }
  49299. if (!this._targetHost) {
  49300. if (this.panningDistanceLimit) {
  49301. this._transformedDirection.addInPlace(this._target);
  49302. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49303. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49304. this._target.copyFrom(this._transformedDirection);
  49305. }
  49306. }
  49307. else {
  49308. this._target.addInPlace(this._transformedDirection);
  49309. }
  49310. }
  49311. this.inertialPanningX *= this.panningInertia;
  49312. this.inertialPanningY *= this.panningInertia;
  49313. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49314. this.inertialPanningX = 0;
  49315. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49316. this.inertialPanningY = 0;
  49317. }
  49318. // Limits
  49319. this._checkLimits();
  49320. _super.prototype._checkInputs.call(this);
  49321. };
  49322. ArcRotateCamera.prototype._checkLimits = function () {
  49323. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49324. if (this.allowUpsideDown && this.beta > Math.PI) {
  49325. this.beta = this.beta - (2 * Math.PI);
  49326. }
  49327. }
  49328. else {
  49329. if (this.beta < this.lowerBetaLimit) {
  49330. this.beta = this.lowerBetaLimit;
  49331. }
  49332. }
  49333. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49334. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49335. this.beta = this.beta + (2 * Math.PI);
  49336. }
  49337. }
  49338. else {
  49339. if (this.beta > this.upperBetaLimit) {
  49340. this.beta = this.upperBetaLimit;
  49341. }
  49342. }
  49343. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49344. this.alpha = this.lowerAlphaLimit;
  49345. }
  49346. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49347. this.alpha = this.upperAlphaLimit;
  49348. }
  49349. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49350. this.radius = this.lowerRadiusLimit;
  49351. }
  49352. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49353. this.radius = this.upperRadiusLimit;
  49354. }
  49355. };
  49356. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49357. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49358. this.radius = this._computationVector.length();
  49359. if (this.radius === 0) {
  49360. this.radius = 0.0001; // Just to avoid division by zero
  49361. }
  49362. // Alpha
  49363. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49364. if (this._computationVector.z < 0) {
  49365. this.alpha = 2 * Math.PI - this.alpha;
  49366. }
  49367. // Beta
  49368. this.beta = Math.acos(this._computationVector.y / this.radius);
  49369. this._checkLimits();
  49370. };
  49371. ArcRotateCamera.prototype.setPosition = function (position) {
  49372. if (this.position.equals(position)) {
  49373. return;
  49374. }
  49375. this.position.copyFrom(position);
  49376. this.rebuildAnglesAndRadius();
  49377. };
  49378. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49379. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49380. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49381. if (target.getBoundingInfo) {
  49382. if (toBoundingCenter) {
  49383. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49384. }
  49385. else {
  49386. this._targetBoundingCenter = null;
  49387. }
  49388. this._targetHost = target;
  49389. this._target = this._getTargetPosition();
  49390. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49391. }
  49392. else {
  49393. var newTarget = target;
  49394. var currentTarget = this._getTargetPosition();
  49395. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49396. return;
  49397. }
  49398. this._targetHost = null;
  49399. this._target = newTarget;
  49400. this._targetBoundingCenter = null;
  49401. this.onMeshTargetChangedObservable.notifyObservers(null);
  49402. }
  49403. this.rebuildAnglesAndRadius();
  49404. };
  49405. ArcRotateCamera.prototype._getViewMatrix = function () {
  49406. // Compute
  49407. var cosa = Math.cos(this.alpha);
  49408. var sina = Math.sin(this.alpha);
  49409. var cosb = Math.cos(this.beta);
  49410. var sinb = Math.sin(this.beta);
  49411. if (sinb === 0) {
  49412. sinb = 0.0001;
  49413. }
  49414. var target = this._getTargetPosition();
  49415. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49416. target.addToRef(this._computationVector, this._newPosition);
  49417. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49418. if (!this._collider) {
  49419. this._collider = new BABYLON.Collider();
  49420. }
  49421. this._collider._radius = this.collisionRadius;
  49422. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49423. this._collisionTriggered = true;
  49424. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49425. }
  49426. else {
  49427. this.position.copyFrom(this._newPosition);
  49428. var up = this.upVector;
  49429. if (this.allowUpsideDown && sinb < 0) {
  49430. up = up.clone();
  49431. up = up.negate();
  49432. }
  49433. this._computeViewMatrix(this.position, target, up);
  49434. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49435. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49436. }
  49437. this._currentTarget = target;
  49438. return this._viewMatrix;
  49439. };
  49440. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49441. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49442. meshes = meshes || this.getScene().meshes;
  49443. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49444. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49445. this.radius = distance * this.zoomOnFactor;
  49446. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49447. };
  49448. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49449. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49450. var meshesOrMinMaxVector;
  49451. var distance;
  49452. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49453. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49454. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49455. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49456. }
  49457. else { //minMaxVector and distance
  49458. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49459. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49460. distance = minMaxVectorAndDistance.distance;
  49461. }
  49462. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49463. if (!doNotUpdateMaxZ) {
  49464. this.maxZ = distance * 2;
  49465. }
  49466. };
  49467. /**
  49468. * @override
  49469. * Override Camera.createRigCamera
  49470. */
  49471. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49472. var alphaShift = 0;
  49473. switch (this.cameraRigMode) {
  49474. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49475. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49476. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49477. case BABYLON.Camera.RIG_MODE_VR:
  49478. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49479. break;
  49480. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49481. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49482. break;
  49483. }
  49484. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49485. rigCam._cameraRigParams = {};
  49486. return rigCam;
  49487. };
  49488. /**
  49489. * @override
  49490. * Override Camera._updateRigCameras
  49491. */
  49492. ArcRotateCamera.prototype._updateRigCameras = function () {
  49493. var camLeft = this._rigCameras[0];
  49494. var camRight = this._rigCameras[1];
  49495. camLeft.beta = camRight.beta = this.beta;
  49496. camLeft.radius = camRight.radius = this.radius;
  49497. switch (this.cameraRigMode) {
  49498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49500. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49501. case BABYLON.Camera.RIG_MODE_VR:
  49502. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49503. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49504. break;
  49505. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49506. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49507. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49508. break;
  49509. }
  49510. _super.prototype._updateRigCameras.call(this);
  49511. };
  49512. ArcRotateCamera.prototype.dispose = function () {
  49513. this.inputs.clear();
  49514. _super.prototype.dispose.call(this);
  49515. };
  49516. ArcRotateCamera.prototype.getClassName = function () {
  49517. return "ArcRotateCamera";
  49518. };
  49519. __decorate([
  49520. BABYLON.serialize()
  49521. ], ArcRotateCamera.prototype, "alpha", void 0);
  49522. __decorate([
  49523. BABYLON.serialize()
  49524. ], ArcRotateCamera.prototype, "beta", void 0);
  49525. __decorate([
  49526. BABYLON.serialize()
  49527. ], ArcRotateCamera.prototype, "radius", void 0);
  49528. __decorate([
  49529. BABYLON.serializeAsVector3("target")
  49530. ], ArcRotateCamera.prototype, "_target", void 0);
  49531. __decorate([
  49532. BABYLON.serialize()
  49533. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49534. __decorate([
  49535. BABYLON.serialize()
  49536. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49537. __decorate([
  49538. BABYLON.serialize()
  49539. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49540. __decorate([
  49541. BABYLON.serialize()
  49542. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49543. __decorate([
  49544. BABYLON.serialize()
  49545. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49546. __decorate([
  49547. BABYLON.serialize()
  49548. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49549. __decorate([
  49550. BABYLON.serialize()
  49551. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49552. __decorate([
  49553. BABYLON.serialize()
  49554. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49555. __decorate([
  49556. BABYLON.serialize()
  49557. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49558. __decorate([
  49559. BABYLON.serialize()
  49560. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49561. __decorate([
  49562. BABYLON.serialize()
  49563. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49564. __decorate([
  49565. BABYLON.serialize()
  49566. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49567. __decorate([
  49568. BABYLON.serialize()
  49569. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49570. __decorate([
  49571. BABYLON.serializeAsVector3()
  49572. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49573. __decorate([
  49574. BABYLON.serialize()
  49575. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49576. __decorate([
  49577. BABYLON.serialize()
  49578. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49579. __decorate([
  49580. BABYLON.serialize()
  49581. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49582. return ArcRotateCamera;
  49583. }(BABYLON.TargetCamera));
  49584. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49585. })(BABYLON || (BABYLON = {}));
  49586. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49587. var BABYLON;
  49588. (function (BABYLON) {
  49589. /**
  49590. * The HemisphericLight simulates the ambient environment light,
  49591. * so the passed direction is the light reflection direction, not the incoming direction.
  49592. */
  49593. var HemisphericLight = /** @class */ (function (_super) {
  49594. __extends(HemisphericLight, _super);
  49595. /**
  49596. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49597. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49598. * The HemisphericLight can't cast shadows.
  49599. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49600. * @param name The friendly name of the light
  49601. * @param direction The direction of the light reflection
  49602. * @param scene The scene the light belongs to
  49603. */
  49604. function HemisphericLight(name, direction, scene) {
  49605. var _this = _super.call(this, name, scene) || this;
  49606. /**
  49607. * The groundColor is the light in the opposite direction to the one specified during creation.
  49608. * 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.
  49609. */
  49610. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49611. _this.direction = direction || BABYLON.Vector3.Up();
  49612. return _this;
  49613. }
  49614. HemisphericLight.prototype._buildUniformLayout = function () {
  49615. this._uniformBuffer.addUniform("vLightData", 4);
  49616. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49617. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49618. this._uniformBuffer.addUniform("vLightGround", 3);
  49619. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49620. this._uniformBuffer.addUniform("depthValues", 2);
  49621. this._uniformBuffer.create();
  49622. };
  49623. /**
  49624. * Returns the string "HemisphericLight".
  49625. * @return The class name
  49626. */
  49627. HemisphericLight.prototype.getClassName = function () {
  49628. return "HemisphericLight";
  49629. };
  49630. /**
  49631. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49632. * Returns the updated direction.
  49633. * @param target The target the direction should point to
  49634. * @return The computed direction
  49635. */
  49636. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49637. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49638. return this.direction;
  49639. };
  49640. /**
  49641. * Returns the shadow generator associated to the light.
  49642. * @returns Always null for hemispheric lights because it does not support shadows.
  49643. */
  49644. HemisphericLight.prototype.getShadowGenerator = function () {
  49645. return null;
  49646. };
  49647. /**
  49648. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49649. * @param effect The effect to update
  49650. * @param lightIndex The index of the light in the effect to update
  49651. * @returns The hemispheric light
  49652. */
  49653. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49654. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49655. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49656. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49657. return this;
  49658. };
  49659. /**
  49660. * @hidden internal use only.
  49661. */
  49662. HemisphericLight.prototype._getWorldMatrix = function () {
  49663. if (!this._worldMatrix) {
  49664. this._worldMatrix = BABYLON.Matrix.Identity();
  49665. }
  49666. return this._worldMatrix;
  49667. };
  49668. /**
  49669. * Returns the integer 3.
  49670. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49671. */
  49672. HemisphericLight.prototype.getTypeID = function () {
  49673. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49674. };
  49675. __decorate([
  49676. BABYLON.serializeAsColor3()
  49677. ], HemisphericLight.prototype, "groundColor", void 0);
  49678. __decorate([
  49679. BABYLON.serializeAsVector3()
  49680. ], HemisphericLight.prototype, "direction", void 0);
  49681. return HemisphericLight;
  49682. }(BABYLON.Light));
  49683. BABYLON.HemisphericLight = HemisphericLight;
  49684. })(BABYLON || (BABYLON = {}));
  49685. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49686. var BABYLON;
  49687. (function (BABYLON) {
  49688. /**
  49689. * Base implementation IShadowLight
  49690. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49691. */
  49692. var ShadowLight = /** @class */ (function (_super) {
  49693. __extends(ShadowLight, _super);
  49694. function ShadowLight() {
  49695. var _this = _super !== null && _super.apply(this, arguments) || this;
  49696. _this._needProjectionMatrixCompute = true;
  49697. return _this;
  49698. }
  49699. ShadowLight.prototype._setPosition = function (value) {
  49700. this._position = value;
  49701. };
  49702. Object.defineProperty(ShadowLight.prototype, "position", {
  49703. /**
  49704. * Sets the position the shadow will be casted from. Also use as the light position for both
  49705. * point and spot lights.
  49706. */
  49707. get: function () {
  49708. return this._position;
  49709. },
  49710. /**
  49711. * Sets the position the shadow will be casted from. Also use as the light position for both
  49712. * point and spot lights.
  49713. */
  49714. set: function (value) {
  49715. this._setPosition(value);
  49716. },
  49717. enumerable: true,
  49718. configurable: true
  49719. });
  49720. ShadowLight.prototype._setDirection = function (value) {
  49721. this._direction = value;
  49722. };
  49723. Object.defineProperty(ShadowLight.prototype, "direction", {
  49724. /**
  49725. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49726. * Also use as the light direction on spot and directional lights.
  49727. */
  49728. get: function () {
  49729. return this._direction;
  49730. },
  49731. /**
  49732. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49733. * Also use as the light direction on spot and directional lights.
  49734. */
  49735. set: function (value) {
  49736. this._setDirection(value);
  49737. },
  49738. enumerable: true,
  49739. configurable: true
  49740. });
  49741. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49742. /**
  49743. * Gets the shadow projection clipping minimum z value.
  49744. */
  49745. get: function () {
  49746. return this._shadowMinZ;
  49747. },
  49748. /**
  49749. * Sets the shadow projection clipping minimum z value.
  49750. */
  49751. set: function (value) {
  49752. this._shadowMinZ = value;
  49753. this.forceProjectionMatrixCompute();
  49754. },
  49755. enumerable: true,
  49756. configurable: true
  49757. });
  49758. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49759. /**
  49760. * Sets the shadow projection clipping maximum z value.
  49761. */
  49762. get: function () {
  49763. return this._shadowMaxZ;
  49764. },
  49765. /**
  49766. * Gets the shadow projection clipping maximum z value.
  49767. */
  49768. set: function (value) {
  49769. this._shadowMaxZ = value;
  49770. this.forceProjectionMatrixCompute();
  49771. },
  49772. enumerable: true,
  49773. configurable: true
  49774. });
  49775. /**
  49776. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49777. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49778. */
  49779. ShadowLight.prototype.computeTransformedInformation = function () {
  49780. if (this.parent && this.parent.getWorldMatrix) {
  49781. if (!this.transformedPosition) {
  49782. this.transformedPosition = BABYLON.Vector3.Zero();
  49783. }
  49784. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49785. // In case the direction is present.
  49786. if (this.direction) {
  49787. if (!this.transformedDirection) {
  49788. this.transformedDirection = BABYLON.Vector3.Zero();
  49789. }
  49790. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49791. }
  49792. return true;
  49793. }
  49794. return false;
  49795. };
  49796. /**
  49797. * Return the depth scale used for the shadow map.
  49798. * @returns the depth scale.
  49799. */
  49800. ShadowLight.prototype.getDepthScale = function () {
  49801. return 50.0;
  49802. };
  49803. /**
  49804. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49805. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49806. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49807. */
  49808. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49809. return this.transformedDirection ? this.transformedDirection : this.direction;
  49810. };
  49811. /**
  49812. * Returns the ShadowLight absolute position in the World.
  49813. * @returns the position vector in world space
  49814. */
  49815. ShadowLight.prototype.getAbsolutePosition = function () {
  49816. return this.transformedPosition ? this.transformedPosition : this.position;
  49817. };
  49818. /**
  49819. * Sets the ShadowLight direction toward the passed target.
  49820. * @param target The point tot target in local space
  49821. * @returns the updated ShadowLight direction
  49822. */
  49823. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49824. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49825. return this.direction;
  49826. };
  49827. /**
  49828. * Returns the light rotation in euler definition.
  49829. * @returns the x y z rotation in local space.
  49830. */
  49831. ShadowLight.prototype.getRotation = function () {
  49832. this.direction.normalize();
  49833. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49834. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49835. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49836. };
  49837. /**
  49838. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49839. * @returns true if a cube texture needs to be use
  49840. */
  49841. ShadowLight.prototype.needCube = function () {
  49842. return false;
  49843. };
  49844. /**
  49845. * Detects if the projection matrix requires to be recomputed this frame.
  49846. * @returns true if it requires to be recomputed otherwise, false.
  49847. */
  49848. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49849. return this._needProjectionMatrixCompute;
  49850. };
  49851. /**
  49852. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49853. */
  49854. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49855. this._needProjectionMatrixCompute = true;
  49856. };
  49857. /**
  49858. * Get the world matrix of the sahdow lights.
  49859. * @hidden Internal Use Only
  49860. */
  49861. ShadowLight.prototype._getWorldMatrix = function () {
  49862. if (!this._worldMatrix) {
  49863. this._worldMatrix = BABYLON.Matrix.Identity();
  49864. }
  49865. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49866. return this._worldMatrix;
  49867. };
  49868. /**
  49869. * Gets the minZ used for shadow according to both the scene and the light.
  49870. * @param activeCamera The camera we are returning the min for
  49871. * @returns the depth min z
  49872. */
  49873. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49874. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49875. };
  49876. /**
  49877. * Gets the maxZ used for shadow according to both the scene and the light.
  49878. * @param activeCamera The camera we are returning the max for
  49879. * @returns the depth max z
  49880. */
  49881. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49882. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49883. };
  49884. /**
  49885. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49886. * @param matrix The materix to updated with the projection information
  49887. * @param viewMatrix The transform matrix of the light
  49888. * @param renderList The list of mesh to render in the map
  49889. * @returns The current light
  49890. */
  49891. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49892. if (this.customProjectionMatrixBuilder) {
  49893. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49894. }
  49895. else {
  49896. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49897. }
  49898. return this;
  49899. };
  49900. __decorate([
  49901. BABYLON.serializeAsVector3()
  49902. ], ShadowLight.prototype, "position", null);
  49903. __decorate([
  49904. BABYLON.serializeAsVector3()
  49905. ], ShadowLight.prototype, "direction", null);
  49906. __decorate([
  49907. BABYLON.serialize()
  49908. ], ShadowLight.prototype, "shadowMinZ", null);
  49909. __decorate([
  49910. BABYLON.serialize()
  49911. ], ShadowLight.prototype, "shadowMaxZ", null);
  49912. return ShadowLight;
  49913. }(BABYLON.Light));
  49914. BABYLON.ShadowLight = ShadowLight;
  49915. })(BABYLON || (BABYLON = {}));
  49916. //# sourceMappingURL=babylon.shadowLight.js.map
  49917. var BABYLON;
  49918. (function (BABYLON) {
  49919. /**
  49920. * A point light is a light defined by an unique point in world space.
  49921. * The light is emitted in every direction from this point.
  49922. * A good example of a point light is a standard light bulb.
  49923. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49924. */
  49925. var PointLight = /** @class */ (function (_super) {
  49926. __extends(PointLight, _super);
  49927. /**
  49928. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49929. * A PointLight emits the light in every direction.
  49930. * It can cast shadows.
  49931. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49932. * ```javascript
  49933. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49934. * ```
  49935. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49936. * @param name The light friendly name
  49937. * @param position The position of the point light in the scene
  49938. * @param scene The scene the lights belongs to
  49939. */
  49940. function PointLight(name, position, scene) {
  49941. var _this = _super.call(this, name, scene) || this;
  49942. _this._shadowAngle = Math.PI / 2;
  49943. _this.position = position;
  49944. return _this;
  49945. }
  49946. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49947. /**
  49948. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49949. * This specifies what angle the shadow will use to be created.
  49950. *
  49951. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49952. */
  49953. get: function () {
  49954. return this._shadowAngle;
  49955. },
  49956. /**
  49957. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49958. * This specifies what angle the shadow will use to be created.
  49959. *
  49960. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49961. */
  49962. set: function (value) {
  49963. this._shadowAngle = value;
  49964. this.forceProjectionMatrixCompute();
  49965. },
  49966. enumerable: true,
  49967. configurable: true
  49968. });
  49969. Object.defineProperty(PointLight.prototype, "direction", {
  49970. /**
  49971. * Gets the direction if it has been set.
  49972. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49973. */
  49974. get: function () {
  49975. return this._direction;
  49976. },
  49977. /**
  49978. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49979. */
  49980. set: function (value) {
  49981. var previousNeedCube = this.needCube();
  49982. this._direction = value;
  49983. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49984. this._shadowGenerator.recreateShadowMap();
  49985. }
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. /**
  49991. * Returns the string "PointLight"
  49992. * @returns the class name
  49993. */
  49994. PointLight.prototype.getClassName = function () {
  49995. return "PointLight";
  49996. };
  49997. /**
  49998. * Returns the integer 0.
  49999. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50000. */
  50001. PointLight.prototype.getTypeID = function () {
  50002. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50003. };
  50004. /**
  50005. * Specifies wether or not the shadowmap should be a cube texture.
  50006. * @returns true if the shadowmap needs to be a cube texture.
  50007. */
  50008. PointLight.prototype.needCube = function () {
  50009. return !this.direction;
  50010. };
  50011. /**
  50012. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50013. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50014. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50015. */
  50016. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50017. if (this.direction) {
  50018. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50019. }
  50020. else {
  50021. switch (faceIndex) {
  50022. case 0:
  50023. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50024. case 1:
  50025. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50026. case 2:
  50027. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50028. case 3:
  50029. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50030. case 4:
  50031. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50032. case 5:
  50033. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50034. }
  50035. }
  50036. return BABYLON.Vector3.Zero();
  50037. };
  50038. /**
  50039. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50040. * - fov = PI / 2
  50041. * - aspect ratio : 1.0
  50042. * - z-near and far equal to the active camera minZ and maxZ.
  50043. * Returns the PointLight.
  50044. */
  50045. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50046. var activeCamera = this.getScene().activeCamera;
  50047. if (!activeCamera) {
  50048. return;
  50049. }
  50050. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50051. };
  50052. PointLight.prototype._buildUniformLayout = function () {
  50053. this._uniformBuffer.addUniform("vLightData", 4);
  50054. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50055. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50056. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50057. this._uniformBuffer.addUniform("depthValues", 2);
  50058. this._uniformBuffer.create();
  50059. };
  50060. /**
  50061. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50062. * @param effect The effect to update
  50063. * @param lightIndex The index of the light in the effect to update
  50064. * @returns The point light
  50065. */
  50066. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50067. if (this.computeTransformedInformation()) {
  50068. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50069. return this;
  50070. }
  50071. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50072. return this;
  50073. };
  50074. __decorate([
  50075. BABYLON.serialize()
  50076. ], PointLight.prototype, "shadowAngle", null);
  50077. return PointLight;
  50078. }(BABYLON.ShadowLight));
  50079. BABYLON.PointLight = PointLight;
  50080. })(BABYLON || (BABYLON = {}));
  50081. //# sourceMappingURL=babylon.pointLight.js.map
  50082. var BABYLON;
  50083. (function (BABYLON) {
  50084. /**
  50085. * A directional light is defined by a direction (what a surprise!).
  50086. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50087. * 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.
  50088. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50089. */
  50090. var DirectionalLight = /** @class */ (function (_super) {
  50091. __extends(DirectionalLight, _super);
  50092. /**
  50093. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50094. * The directional light is emitted from everywhere in the given direction.
  50095. * It can cast shawdows.
  50096. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50097. * @param name The friendly name of the light
  50098. * @param direction The direction of the light
  50099. * @param scene The scene the light belongs to
  50100. */
  50101. function DirectionalLight(name, direction, scene) {
  50102. var _this = _super.call(this, name, scene) || this;
  50103. _this._shadowFrustumSize = 0;
  50104. _this._shadowOrthoScale = 0.1;
  50105. /**
  50106. * Automatically compute the projection matrix to best fit (including all the casters)
  50107. * on each frame.
  50108. */
  50109. _this.autoUpdateExtends = true;
  50110. // Cache
  50111. _this._orthoLeft = Number.MAX_VALUE;
  50112. _this._orthoRight = Number.MIN_VALUE;
  50113. _this._orthoTop = Number.MIN_VALUE;
  50114. _this._orthoBottom = Number.MAX_VALUE;
  50115. _this.position = direction.scale(-1.0);
  50116. _this.direction = direction;
  50117. return _this;
  50118. }
  50119. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50120. /**
  50121. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50122. */
  50123. get: function () {
  50124. return this._shadowFrustumSize;
  50125. },
  50126. /**
  50127. * Specifies a fix frustum size for the shadow generation.
  50128. */
  50129. set: function (value) {
  50130. this._shadowFrustumSize = value;
  50131. this.forceProjectionMatrixCompute();
  50132. },
  50133. enumerable: true,
  50134. configurable: true
  50135. });
  50136. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50137. /**
  50138. * Gets the shadow projection scale against the optimal computed one.
  50139. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50140. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50141. */
  50142. get: function () {
  50143. return this._shadowOrthoScale;
  50144. },
  50145. /**
  50146. * Sets the shadow projection scale against the optimal computed one.
  50147. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50148. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50149. */
  50150. set: function (value) {
  50151. this._shadowOrthoScale = value;
  50152. this.forceProjectionMatrixCompute();
  50153. },
  50154. enumerable: true,
  50155. configurable: true
  50156. });
  50157. /**
  50158. * Returns the string "DirectionalLight".
  50159. * @return The class name
  50160. */
  50161. DirectionalLight.prototype.getClassName = function () {
  50162. return "DirectionalLight";
  50163. };
  50164. /**
  50165. * Returns the integer 1.
  50166. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50167. */
  50168. DirectionalLight.prototype.getTypeID = function () {
  50169. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50170. };
  50171. /**
  50172. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50173. * Returns the DirectionalLight Shadow projection matrix.
  50174. */
  50175. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50176. if (this.shadowFrustumSize > 0) {
  50177. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50178. }
  50179. else {
  50180. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50181. }
  50182. };
  50183. /**
  50184. * Sets the passed matrix "matrix" as fixed frustum 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._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50188. var activeCamera = this.getScene().activeCamera;
  50189. if (!activeCamera) {
  50190. return;
  50191. }
  50192. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50193. };
  50194. /**
  50195. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50196. * Returns the DirectionalLight Shadow projection matrix.
  50197. */
  50198. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50199. var activeCamera = this.getScene().activeCamera;
  50200. if (!activeCamera) {
  50201. return;
  50202. }
  50203. // Check extends
  50204. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50205. var tempVector3 = BABYLON.Vector3.Zero();
  50206. this._orthoLeft = Number.MAX_VALUE;
  50207. this._orthoRight = Number.MIN_VALUE;
  50208. this._orthoTop = Number.MIN_VALUE;
  50209. this._orthoBottom = Number.MAX_VALUE;
  50210. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50211. var mesh = renderList[meshIndex];
  50212. if (!mesh) {
  50213. continue;
  50214. }
  50215. var boundingInfo = mesh.getBoundingInfo();
  50216. var boundingBox = boundingInfo.boundingBox;
  50217. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50218. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50219. if (tempVector3.x < this._orthoLeft)
  50220. this._orthoLeft = tempVector3.x;
  50221. if (tempVector3.y < this._orthoBottom)
  50222. this._orthoBottom = tempVector3.y;
  50223. if (tempVector3.x > this._orthoRight)
  50224. this._orthoRight = tempVector3.x;
  50225. if (tempVector3.y > this._orthoTop)
  50226. this._orthoTop = tempVector3.y;
  50227. }
  50228. }
  50229. }
  50230. var xOffset = this._orthoRight - this._orthoLeft;
  50231. var yOffset = this._orthoTop - this._orthoBottom;
  50232. 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);
  50233. };
  50234. DirectionalLight.prototype._buildUniformLayout = function () {
  50235. this._uniformBuffer.addUniform("vLightData", 4);
  50236. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50237. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50238. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50239. this._uniformBuffer.addUniform("depthValues", 2);
  50240. this._uniformBuffer.create();
  50241. };
  50242. /**
  50243. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50244. * @param effect The effect to update
  50245. * @param lightIndex The index of the light in the effect to update
  50246. * @returns The directional light
  50247. */
  50248. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50249. if (this.computeTransformedInformation()) {
  50250. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50251. return this;
  50252. }
  50253. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50254. return this;
  50255. };
  50256. /**
  50257. * Gets the minZ used for shadow according to both the scene and the light.
  50258. *
  50259. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50260. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50261. * @param activeCamera The camera we are returning the min for
  50262. * @returns the depth min z
  50263. */
  50264. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50265. return 1;
  50266. };
  50267. /**
  50268. * Gets the maxZ used for shadow according to both the scene and the light.
  50269. *
  50270. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50271. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50272. * @param activeCamera The camera we are returning the max for
  50273. * @returns the depth max z
  50274. */
  50275. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50276. return 1;
  50277. };
  50278. __decorate([
  50279. BABYLON.serialize()
  50280. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50281. __decorate([
  50282. BABYLON.serialize()
  50283. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50284. __decorate([
  50285. BABYLON.serialize()
  50286. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50287. return DirectionalLight;
  50288. }(BABYLON.ShadowLight));
  50289. BABYLON.DirectionalLight = DirectionalLight;
  50290. })(BABYLON || (BABYLON = {}));
  50291. //# sourceMappingURL=babylon.directionalLight.js.map
  50292. var BABYLON;
  50293. (function (BABYLON) {
  50294. /**
  50295. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50296. * These values define a cone of light starting from the position, emitting toward the direction.
  50297. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50298. * and the exponent defines the speed of the decay of the light with distance (reach).
  50299. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50300. */
  50301. var SpotLight = /** @class */ (function (_super) {
  50302. __extends(SpotLight, _super);
  50303. /**
  50304. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50305. * It can cast shadows.
  50306. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50307. * @param name The light friendly name
  50308. * @param position The position of the spot light in the scene
  50309. * @param direction The direction of the light in the scene
  50310. * @param angle The cone angle of the light in Radians
  50311. * @param exponent The light decay speed with the distance from the emission spot
  50312. * @param scene The scene the lights belongs to
  50313. */
  50314. function SpotLight(name, position, direction, angle, exponent, scene) {
  50315. var _this = _super.call(this, name, scene) || this;
  50316. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50317. _this._projectionTextureLightNear = 1e-6;
  50318. _this._projectionTextureLightFar = 1000.0;
  50319. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50320. _this._projectionTextureViewLightDirty = true;
  50321. _this._projectionTextureProjectionLightDirty = true;
  50322. _this._projectionTextureDirty = true;
  50323. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50324. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50325. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50326. _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);
  50327. _this.position = position;
  50328. _this.direction = direction;
  50329. _this.angle = angle;
  50330. _this.exponent = exponent;
  50331. return _this;
  50332. }
  50333. Object.defineProperty(SpotLight.prototype, "angle", {
  50334. /**
  50335. * Gets the cone angle of the spot light in Radians.
  50336. */
  50337. get: function () {
  50338. return this._angle;
  50339. },
  50340. /**
  50341. * Sets the cone angle of the spot light in Radians.
  50342. */
  50343. set: function (value) {
  50344. this._angle = value;
  50345. this._projectionTextureProjectionLightDirty = true;
  50346. this.forceProjectionMatrixCompute();
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50352. /**
  50353. * Allows scaling the angle of the light for shadow generation only.
  50354. */
  50355. get: function () {
  50356. return this._shadowAngleScale;
  50357. },
  50358. /**
  50359. * Allows scaling the angle of the light for shadow generation only.
  50360. */
  50361. set: function (value) {
  50362. this._shadowAngleScale = value;
  50363. this.forceProjectionMatrixCompute();
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50369. /**
  50370. * Allows reading the projecton texture
  50371. */
  50372. get: function () {
  50373. return this._projectionTextureMatrix;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50379. /**
  50380. * Gets the near clip of the Spotlight for texture projection.
  50381. */
  50382. get: function () {
  50383. return this._projectionTextureLightNear;
  50384. },
  50385. /**
  50386. * Sets the near clip of the Spotlight for texture projection.
  50387. */
  50388. set: function (value) {
  50389. this._projectionTextureLightNear = value;
  50390. this._projectionTextureProjectionLightDirty = true;
  50391. },
  50392. enumerable: true,
  50393. configurable: true
  50394. });
  50395. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50396. /**
  50397. * Gets the far clip of the Spotlight for texture projection.
  50398. */
  50399. get: function () {
  50400. return this._projectionTextureLightFar;
  50401. },
  50402. /**
  50403. * Sets the far clip of the Spotlight for texture projection.
  50404. */
  50405. set: function (value) {
  50406. this._projectionTextureLightFar = value;
  50407. this._projectionTextureProjectionLightDirty = true;
  50408. },
  50409. enumerable: true,
  50410. configurable: true
  50411. });
  50412. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50413. /**
  50414. * Gets the Up vector of the Spotlight for texture projection.
  50415. */
  50416. get: function () {
  50417. return this._projectionTextureUpDirection;
  50418. },
  50419. /**
  50420. * Sets the Up vector of the Spotlight for texture projection.
  50421. */
  50422. set: function (value) {
  50423. this._projectionTextureUpDirection = value;
  50424. this._projectionTextureProjectionLightDirty = true;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50430. /**
  50431. * Gets the projection texture of the light.
  50432. */
  50433. get: function () {
  50434. return this._projectionTexture;
  50435. },
  50436. /**
  50437. * Sets the projection texture of the light.
  50438. */
  50439. set: function (value) {
  50440. this._projectionTexture = value;
  50441. this._projectionTextureDirty = true;
  50442. },
  50443. enumerable: true,
  50444. configurable: true
  50445. });
  50446. /**
  50447. * Returns the string "SpotLight".
  50448. * @returns the class name
  50449. */
  50450. SpotLight.prototype.getClassName = function () {
  50451. return "SpotLight";
  50452. };
  50453. /**
  50454. * Returns the integer 2.
  50455. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50456. */
  50457. SpotLight.prototype.getTypeID = function () {
  50458. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50459. };
  50460. /**
  50461. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50462. */
  50463. SpotLight.prototype._setDirection = function (value) {
  50464. _super.prototype._setDirection.call(this, value);
  50465. this._projectionTextureViewLightDirty = true;
  50466. };
  50467. /**
  50468. * Overrides the position setter to recompute the projection texture view light Matrix.
  50469. */
  50470. SpotLight.prototype._setPosition = function (value) {
  50471. _super.prototype._setPosition.call(this, value);
  50472. this._projectionTextureViewLightDirty = true;
  50473. };
  50474. /**
  50475. * 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.
  50476. * Returns the SpotLight.
  50477. */
  50478. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50479. var activeCamera = this.getScene().activeCamera;
  50480. if (!activeCamera) {
  50481. return;
  50482. }
  50483. this._shadowAngleScale = this._shadowAngleScale || 1;
  50484. var angle = this._shadowAngleScale * this._angle;
  50485. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50486. };
  50487. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50488. this._projectionTextureViewLightDirty = false;
  50489. this._projectionTextureDirty = true;
  50490. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50491. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50492. };
  50493. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50494. this._projectionTextureProjectionLightDirty = false;
  50495. this._projectionTextureDirty = true;
  50496. var light_far = this.projectionTextureLightFar;
  50497. var light_near = this.projectionTextureLightNear;
  50498. var P = light_far / (light_far - light_near);
  50499. var Q = -P * light_near;
  50500. var S = 1.0 / Math.tan(this._angle / 2.0);
  50501. var A = 1.0;
  50502. 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);
  50503. };
  50504. /**
  50505. * Main function for light texture projection matrix computing.
  50506. */
  50507. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50508. this._projectionTextureDirty = false;
  50509. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50510. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50511. };
  50512. SpotLight.prototype._buildUniformLayout = function () {
  50513. this._uniformBuffer.addUniform("vLightData", 4);
  50514. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50515. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50516. this._uniformBuffer.addUniform("vLightDirection", 3);
  50517. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50518. this._uniformBuffer.addUniform("depthValues", 2);
  50519. this._uniformBuffer.create();
  50520. };
  50521. /**
  50522. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50523. * @param effect The effect to update
  50524. * @param lightIndex The index of the light in the effect to update
  50525. * @returns The spot light
  50526. */
  50527. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50528. var normalizeDirection;
  50529. if (this.computeTransformedInformation()) {
  50530. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50531. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50532. }
  50533. else {
  50534. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50535. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50536. }
  50537. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50538. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50539. if (this._projectionTextureViewLightDirty) {
  50540. this._computeProjectionTextureViewLightMatrix();
  50541. }
  50542. if (this._projectionTextureProjectionLightDirty) {
  50543. this._computeProjectionTextureProjectionLightMatrix();
  50544. }
  50545. if (this._projectionTextureDirty) {
  50546. this._computeProjectionTextureMatrix();
  50547. }
  50548. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50549. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50550. }
  50551. return this;
  50552. };
  50553. /**
  50554. * Disposes the light and the associated resources.
  50555. */
  50556. SpotLight.prototype.dispose = function () {
  50557. _super.prototype.dispose.call(this);
  50558. if (this._projectionTexture) {
  50559. this._projectionTexture.dispose();
  50560. }
  50561. };
  50562. __decorate([
  50563. BABYLON.serialize()
  50564. ], SpotLight.prototype, "angle", null);
  50565. __decorate([
  50566. BABYLON.serialize()
  50567. ], SpotLight.prototype, "shadowAngleScale", null);
  50568. __decorate([
  50569. BABYLON.serialize()
  50570. ], SpotLight.prototype, "exponent", void 0);
  50571. __decorate([
  50572. BABYLON.serialize()
  50573. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50574. __decorate([
  50575. BABYLON.serialize()
  50576. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50577. __decorate([
  50578. BABYLON.serialize()
  50579. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50580. __decorate([
  50581. BABYLON.serializeAsTexture("projectedLightTexture")
  50582. ], SpotLight.prototype, "_projectionTexture", void 0);
  50583. return SpotLight;
  50584. }(BABYLON.ShadowLight));
  50585. BABYLON.SpotLight = SpotLight;
  50586. })(BABYLON || (BABYLON = {}));
  50587. //# sourceMappingURL=babylon.spotLight.js.map
  50588. var BABYLON;
  50589. (function (BABYLON) {
  50590. /**
  50591. * Class used to override all child animations of a given target
  50592. */
  50593. var AnimationPropertiesOverride = /** @class */ (function () {
  50594. function AnimationPropertiesOverride() {
  50595. /**
  50596. * Gets or sets a value indicating if animation blending must be used
  50597. */
  50598. this.enableBlending = false;
  50599. /**
  50600. * Gets or sets the blending speed to use when enableBlending is true
  50601. */
  50602. this.blendingSpeed = 0.01;
  50603. /**
  50604. * Gets or sets the default loop mode to use
  50605. */
  50606. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50607. }
  50608. return AnimationPropertiesOverride;
  50609. }());
  50610. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50611. })(BABYLON || (BABYLON = {}));
  50612. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50613. var BABYLON;
  50614. (function (BABYLON) {
  50615. /**
  50616. * Represents the range of an animation
  50617. */
  50618. var AnimationRange = /** @class */ (function () {
  50619. /**
  50620. * Initializes the range of an animation
  50621. * @param name The name of the animation range
  50622. * @param from The starting frame of the animation
  50623. * @param to The ending frame of the animation
  50624. */
  50625. function AnimationRange(
  50626. /**The name of the animation range**/
  50627. name,
  50628. /**The starting frame of the animation */
  50629. from,
  50630. /**The ending frame of the animation*/
  50631. to) {
  50632. this.name = name;
  50633. this.from = from;
  50634. this.to = to;
  50635. }
  50636. /**
  50637. * Makes a copy of the animation range
  50638. * @returns A copy of the animation range
  50639. */
  50640. AnimationRange.prototype.clone = function () {
  50641. return new AnimationRange(this.name, this.from, this.to);
  50642. };
  50643. return AnimationRange;
  50644. }());
  50645. BABYLON.AnimationRange = AnimationRange;
  50646. /**
  50647. * Composed of a frame, and an action function
  50648. */
  50649. var AnimationEvent = /** @class */ (function () {
  50650. /**
  50651. * Initializes the animation event
  50652. * @param frame The frame for which the event is triggered
  50653. * @param action The event to perform when triggered
  50654. * @param onlyOnce Specifies if the event should be triggered only once
  50655. */
  50656. function AnimationEvent(
  50657. /** The frame for which the event is triggered **/
  50658. frame,
  50659. /** The event to perform when triggered **/
  50660. action,
  50661. /** Specifies if the event should be triggered only once**/
  50662. onlyOnce) {
  50663. this.frame = frame;
  50664. this.action = action;
  50665. this.onlyOnce = onlyOnce;
  50666. /**
  50667. * Specifies if the animation event is done
  50668. */
  50669. this.isDone = false;
  50670. }
  50671. /** @hidden */
  50672. AnimationEvent.prototype._clone = function () {
  50673. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50674. };
  50675. return AnimationEvent;
  50676. }());
  50677. BABYLON.AnimationEvent = AnimationEvent;
  50678. /**
  50679. * A cursor which tracks a point on a path
  50680. */
  50681. var PathCursor = /** @class */ (function () {
  50682. /**
  50683. * Initializes the path cursor
  50684. * @param path The path to track
  50685. */
  50686. function PathCursor(path) {
  50687. this.path = path;
  50688. /**
  50689. * Stores path cursor callbacks for when an onchange event is triggered
  50690. */
  50691. this._onchange = new Array();
  50692. /**
  50693. * The value of the path cursor
  50694. */
  50695. this.value = 0;
  50696. /**
  50697. * The animation array of the path cursor
  50698. */
  50699. this.animations = new Array();
  50700. }
  50701. /**
  50702. * Gets the cursor point on the path
  50703. * @returns A point on the path cursor at the cursor location
  50704. */
  50705. PathCursor.prototype.getPoint = function () {
  50706. var point = this.path.getPointAtLengthPosition(this.value);
  50707. return new BABYLON.Vector3(point.x, 0, point.y);
  50708. };
  50709. /**
  50710. * Moves the cursor ahead by the step amount
  50711. * @param step The amount to move the cursor forward
  50712. * @returns This path cursor
  50713. */
  50714. PathCursor.prototype.moveAhead = function (step) {
  50715. if (step === void 0) { step = 0.002; }
  50716. this.move(step);
  50717. return this;
  50718. };
  50719. /**
  50720. * Moves the cursor behind by the step amount
  50721. * @param step The amount to move the cursor back
  50722. * @returns This path cursor
  50723. */
  50724. PathCursor.prototype.moveBack = function (step) {
  50725. if (step === void 0) { step = 0.002; }
  50726. this.move(-step);
  50727. return this;
  50728. };
  50729. /**
  50730. * Moves the cursor by the step amount
  50731. * If the step amount is greater than one, an exception is thrown
  50732. * @param step The amount to move the cursor
  50733. * @returns This path cursor
  50734. */
  50735. PathCursor.prototype.move = function (step) {
  50736. if (Math.abs(step) > 1) {
  50737. throw "step size should be less than 1.";
  50738. }
  50739. this.value += step;
  50740. this.ensureLimits();
  50741. this.raiseOnChange();
  50742. return this;
  50743. };
  50744. /**
  50745. * Ensures that the value is limited between zero and one
  50746. * @returns This path cursor
  50747. */
  50748. PathCursor.prototype.ensureLimits = function () {
  50749. while (this.value > 1) {
  50750. this.value -= 1;
  50751. }
  50752. while (this.value < 0) {
  50753. this.value += 1;
  50754. }
  50755. return this;
  50756. };
  50757. /**
  50758. * Runs onchange callbacks on change (used by the animation engine)
  50759. * @returns This path cursor
  50760. */
  50761. PathCursor.prototype.raiseOnChange = function () {
  50762. var _this = this;
  50763. this._onchange.forEach(function (f) { return f(_this); });
  50764. return this;
  50765. };
  50766. /**
  50767. * Executes a function on change
  50768. * @param f A path cursor onchange callback
  50769. * @returns This path cursor
  50770. */
  50771. PathCursor.prototype.onchange = function (f) {
  50772. this._onchange.push(f);
  50773. return this;
  50774. };
  50775. return PathCursor;
  50776. }());
  50777. BABYLON.PathCursor = PathCursor;
  50778. /**
  50779. * Enum for the animation key frame interpolation type
  50780. */
  50781. var AnimationKeyInterpolation;
  50782. (function (AnimationKeyInterpolation) {
  50783. /**
  50784. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50785. */
  50786. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50787. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50788. /**
  50789. * Class used to store any kind of animation
  50790. */
  50791. var Animation = /** @class */ (function () {
  50792. /**
  50793. * Initializes the animation
  50794. * @param name Name of the animation
  50795. * @param targetProperty Property to animate
  50796. * @param framePerSecond The frames per second of the animation
  50797. * @param dataType The data type of the animation
  50798. * @param loopMode The loop mode of the animation
  50799. * @param enableBlendings Specifies if blending should be enabled
  50800. */
  50801. function Animation(
  50802. /**Name of the animation */
  50803. name,
  50804. /**Property to animate */
  50805. targetProperty,
  50806. /**The frames per second of the animation */
  50807. framePerSecond,
  50808. /**The data type of the animation */
  50809. dataType,
  50810. /**The loop mode of the animation */
  50811. loopMode,
  50812. /**Specifies if blending should be enabled */
  50813. enableBlending) {
  50814. this.name = name;
  50815. this.targetProperty = targetProperty;
  50816. this.framePerSecond = framePerSecond;
  50817. this.dataType = dataType;
  50818. this.loopMode = loopMode;
  50819. this.enableBlending = enableBlending;
  50820. /**
  50821. * @hidden Internal use only
  50822. */
  50823. this._runtimeAnimations = new Array();
  50824. /**
  50825. * The set of event that will be linked to this animation
  50826. */
  50827. this._events = new Array();
  50828. /**
  50829. * Stores the blending speed of the animation
  50830. */
  50831. this.blendingSpeed = 0.01;
  50832. /**
  50833. * Stores the animation ranges for the animation
  50834. */
  50835. this._ranges = {};
  50836. this.targetPropertyPath = targetProperty.split(".");
  50837. this.dataType = dataType;
  50838. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50839. }
  50840. /**
  50841. * @hidden Internal use
  50842. */
  50843. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50844. var dataType = undefined;
  50845. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50846. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50847. }
  50848. else if (from instanceof BABYLON.Quaternion) {
  50849. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50850. }
  50851. else if (from instanceof BABYLON.Vector3) {
  50852. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50853. }
  50854. else if (from instanceof BABYLON.Vector2) {
  50855. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50856. }
  50857. else if (from instanceof BABYLON.Color3) {
  50858. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50859. }
  50860. else if (from instanceof BABYLON.Size) {
  50861. dataType = Animation.ANIMATIONTYPE_SIZE;
  50862. }
  50863. if (dataType == undefined) {
  50864. return null;
  50865. }
  50866. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50867. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50868. animation.setKeys(keys);
  50869. if (easingFunction !== undefined) {
  50870. animation.setEasingFunction(easingFunction);
  50871. }
  50872. return animation;
  50873. };
  50874. /**
  50875. * Sets up an animation
  50876. * @param property The property to animate
  50877. * @param animationType The animation type to apply
  50878. * @param framePerSecond The frames per second of the animation
  50879. * @param easingFunction The easing function used in the animation
  50880. * @returns The created animation
  50881. */
  50882. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50883. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50884. animation.setEasingFunction(easingFunction);
  50885. return animation;
  50886. };
  50887. /**
  50888. * Create and start an animation on a node
  50889. * @param name defines the name of the global animation that will be run on all nodes
  50890. * @param node defines the root node where the animation will take place
  50891. * @param targetProperty defines property to animate
  50892. * @param framePerSecond defines the number of frame per second yo use
  50893. * @param totalFrame defines the number of frames in total
  50894. * @param from defines the initial value
  50895. * @param to defines the final value
  50896. * @param loopMode defines which loop mode you want to use (off by default)
  50897. * @param easingFunction defines the easing function to use (linear by default)
  50898. * @param onAnimationEnd defines the callback to call when animation end
  50899. * @returns the animatable created for this animation
  50900. */
  50901. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50902. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50903. if (!animation) {
  50904. return null;
  50905. }
  50906. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50907. };
  50908. /**
  50909. * Create and start an animation on a node and its descendants
  50910. * @param name defines the name of the global animation that will be run on all nodes
  50911. * @param node defines the root node where the animation will take place
  50912. * @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
  50913. * @param targetProperty defines property to animate
  50914. * @param framePerSecond defines the number of frame per second to use
  50915. * @param totalFrame defines the number of frames in total
  50916. * @param from defines the initial value
  50917. * @param to defines the final value
  50918. * @param loopMode defines which loop mode you want to use (off by default)
  50919. * @param easingFunction defines the easing function to use (linear by default)
  50920. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50921. * @returns the list of animatables created for all nodes
  50922. * @example https://www.babylonjs-playground.com/#MH0VLI
  50923. */
  50924. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50925. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50926. if (!animation) {
  50927. return null;
  50928. }
  50929. var scene = node.getScene();
  50930. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50931. };
  50932. /**
  50933. * Creates a new animation, merges it with the existing animations and starts it
  50934. * @param name Name of the animation
  50935. * @param node Node which contains the scene that begins the animations
  50936. * @param targetProperty Specifies which property to animate
  50937. * @param framePerSecond The frames per second of the animation
  50938. * @param totalFrame The total number of frames
  50939. * @param from The frame at the beginning of the animation
  50940. * @param to The frame at the end of the animation
  50941. * @param loopMode Specifies the loop mode of the animation
  50942. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50943. * @param onAnimationEnd Callback to run once the animation is complete
  50944. * @returns Nullable animation
  50945. */
  50946. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50947. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50948. if (!animation) {
  50949. return null;
  50950. }
  50951. node.animations.push(animation);
  50952. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50953. };
  50954. /**
  50955. * Transition property of an host to the target Value
  50956. * @param property The property to transition
  50957. * @param targetValue The target Value of the property
  50958. * @param host The object where the property to animate belongs
  50959. * @param scene Scene used to run the animation
  50960. * @param frameRate Framerate (in frame/s) to use
  50961. * @param transition The transition type we want to use
  50962. * @param duration The duration of the animation, in milliseconds
  50963. * @param onAnimationEnd Callback trigger at the end of the animation
  50964. * @returns Nullable animation
  50965. */
  50966. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50967. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50968. if (duration <= 0) {
  50969. host[property] = targetValue;
  50970. if (onAnimationEnd) {
  50971. onAnimationEnd();
  50972. }
  50973. return null;
  50974. }
  50975. var endFrame = frameRate * (duration / 1000);
  50976. transition.setKeys([{
  50977. frame: 0,
  50978. value: host[property].clone ? host[property].clone() : host[property]
  50979. },
  50980. {
  50981. frame: endFrame,
  50982. value: targetValue
  50983. }]);
  50984. if (!host.animations) {
  50985. host.animations = [];
  50986. }
  50987. host.animations.push(transition);
  50988. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50989. animation.onAnimationEnd = onAnimationEnd;
  50990. return animation;
  50991. };
  50992. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50993. /**
  50994. * Return the array of runtime animations currently using this animation
  50995. */
  50996. get: function () {
  50997. return this._runtimeAnimations;
  50998. },
  50999. enumerable: true,
  51000. configurable: true
  51001. });
  51002. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51003. /**
  51004. * Specifies if any of the runtime animations are currently running
  51005. */
  51006. get: function () {
  51007. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51008. var runtimeAnimation = _a[_i];
  51009. if (!runtimeAnimation.isStopped) {
  51010. return true;
  51011. }
  51012. }
  51013. return false;
  51014. },
  51015. enumerable: true,
  51016. configurable: true
  51017. });
  51018. // Methods
  51019. /**
  51020. * Converts the animation to a string
  51021. * @param fullDetails support for multiple levels of logging within scene loading
  51022. * @returns String form of the animation
  51023. */
  51024. Animation.prototype.toString = function (fullDetails) {
  51025. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51026. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51027. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51028. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51029. if (fullDetails) {
  51030. ret += ", Ranges: {";
  51031. var first = true;
  51032. for (var name in this._ranges) {
  51033. if (first) {
  51034. ret += ", ";
  51035. first = false;
  51036. }
  51037. ret += name;
  51038. }
  51039. ret += "}";
  51040. }
  51041. return ret;
  51042. };
  51043. /**
  51044. * Add an event to this animation
  51045. * @param event Event to add
  51046. */
  51047. Animation.prototype.addEvent = function (event) {
  51048. this._events.push(event);
  51049. };
  51050. /**
  51051. * Remove all events found at the given frame
  51052. * @param frame The frame to remove events from
  51053. */
  51054. Animation.prototype.removeEvents = function (frame) {
  51055. for (var index = 0; index < this._events.length; index++) {
  51056. if (this._events[index].frame === frame) {
  51057. this._events.splice(index, 1);
  51058. index--;
  51059. }
  51060. }
  51061. };
  51062. /**
  51063. * Retrieves all the events from the animation
  51064. * @returns Events from the animation
  51065. */
  51066. Animation.prototype.getEvents = function () {
  51067. return this._events;
  51068. };
  51069. /**
  51070. * Creates an animation range
  51071. * @param name Name of the animation range
  51072. * @param from Starting frame of the animation range
  51073. * @param to Ending frame of the animation
  51074. */
  51075. Animation.prototype.createRange = function (name, from, to) {
  51076. // check name not already in use; could happen for bones after serialized
  51077. if (!this._ranges[name]) {
  51078. this._ranges[name] = new AnimationRange(name, from, to);
  51079. }
  51080. };
  51081. /**
  51082. * Deletes an animation range by name
  51083. * @param name Name of the animation range to delete
  51084. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51085. */
  51086. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51087. if (deleteFrames === void 0) { deleteFrames = true; }
  51088. var range = this._ranges[name];
  51089. if (!range) {
  51090. return;
  51091. }
  51092. if (deleteFrames) {
  51093. var from = range.from;
  51094. var to = range.to;
  51095. // this loop MUST go high to low for multiple splices to work
  51096. for (var key = this._keys.length - 1; key >= 0; key--) {
  51097. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51098. this._keys.splice(key, 1);
  51099. }
  51100. }
  51101. }
  51102. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51103. };
  51104. /**
  51105. * Gets the animation range by name, or null if not defined
  51106. * @param name Name of the animation range
  51107. * @returns Nullable animation range
  51108. */
  51109. Animation.prototype.getRange = function (name) {
  51110. return this._ranges[name];
  51111. };
  51112. /**
  51113. * Gets the key frames from the animation
  51114. * @returns The key frames of the animation
  51115. */
  51116. Animation.prototype.getKeys = function () {
  51117. return this._keys;
  51118. };
  51119. /**
  51120. * Gets the highest frame rate of the animation
  51121. * @returns Highest frame rate of the animation
  51122. */
  51123. Animation.prototype.getHighestFrame = function () {
  51124. var ret = 0;
  51125. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51126. if (ret < this._keys[key].frame) {
  51127. ret = this._keys[key].frame;
  51128. }
  51129. }
  51130. return ret;
  51131. };
  51132. /**
  51133. * Gets the easing function of the animation
  51134. * @returns Easing function of the animation
  51135. */
  51136. Animation.prototype.getEasingFunction = function () {
  51137. return this._easingFunction;
  51138. };
  51139. /**
  51140. * Sets the easing function of the animation
  51141. * @param easingFunction A custom mathematical formula for animation
  51142. */
  51143. Animation.prototype.setEasingFunction = function (easingFunction) {
  51144. this._easingFunction = easingFunction;
  51145. };
  51146. /**
  51147. * Interpolates a scalar linearly
  51148. * @param startValue Start value of the animation curve
  51149. * @param endValue End value of the animation curve
  51150. * @param gradient Scalar amount to interpolate
  51151. * @returns Interpolated scalar value
  51152. */
  51153. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51154. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51155. };
  51156. /**
  51157. * Interpolates a scalar cubically
  51158. * @param startValue Start value of the animation curve
  51159. * @param outTangent End tangent of the animation
  51160. * @param endValue End value of the animation curve
  51161. * @param inTangent Start tangent of the animation curve
  51162. * @param gradient Scalar amount to interpolate
  51163. * @returns Interpolated scalar value
  51164. */
  51165. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51166. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51167. };
  51168. /**
  51169. * Interpolates a quaternion using a spherical linear interpolation
  51170. * @param startValue Start value of the animation curve
  51171. * @param endValue End value of the animation curve
  51172. * @param gradient Scalar amount to interpolate
  51173. * @returns Interpolated quaternion value
  51174. */
  51175. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51176. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51177. };
  51178. /**
  51179. * Interpolates a quaternion cubically
  51180. * @param startValue Start value of the animation curve
  51181. * @param outTangent End tangent of the animation curve
  51182. * @param endValue End value of the animation curve
  51183. * @param inTangent Start tangent of the animation curve
  51184. * @param gradient Scalar amount to interpolate
  51185. * @returns Interpolated quaternion value
  51186. */
  51187. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51188. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51189. };
  51190. /**
  51191. * Interpolates a Vector3 linearl
  51192. * @param startValue Start value of the animation curve
  51193. * @param endValue End value of the animation curve
  51194. * @param gradient Scalar amount to interpolate
  51195. * @returns Interpolated scalar value
  51196. */
  51197. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51198. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51199. };
  51200. /**
  51201. * Interpolates a Vector3 cubically
  51202. * @param startValue Start value of the animation curve
  51203. * @param outTangent End tangent of the animation
  51204. * @param endValue End value of the animation curve
  51205. * @param inTangent Start tangent of the animation curve
  51206. * @param gradient Scalar amount to interpolate
  51207. * @returns InterpolatedVector3 value
  51208. */
  51209. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51210. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51211. };
  51212. /**
  51213. * Interpolates a Vector2 linearly
  51214. * @param startValue Start value of the animation curve
  51215. * @param endValue End value of the animation curve
  51216. * @param gradient Scalar amount to interpolate
  51217. * @returns Interpolated Vector2 value
  51218. */
  51219. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51220. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51221. };
  51222. /**
  51223. * Interpolates a Vector2 cubically
  51224. * @param startValue Start value of the animation curve
  51225. * @param outTangent End tangent of the animation
  51226. * @param endValue End value of the animation curve
  51227. * @param inTangent Start tangent of the animation curve
  51228. * @param gradient Scalar amount to interpolate
  51229. * @returns Interpolated Vector2 value
  51230. */
  51231. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51232. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51233. };
  51234. /**
  51235. * Interpolates a size linearly
  51236. * @param startValue Start value of the animation curve
  51237. * @param endValue End value of the animation curve
  51238. * @param gradient Scalar amount to interpolate
  51239. * @returns Interpolated Size value
  51240. */
  51241. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51242. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51243. };
  51244. /**
  51245. * Interpolates a Color3 linearly
  51246. * @param startValue Start value of the animation curve
  51247. * @param endValue End value of the animation curve
  51248. * @param gradient Scalar amount to interpolate
  51249. * @returns Interpolated Color3 value
  51250. */
  51251. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51252. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51253. };
  51254. /**
  51255. * @hidden Internal use only
  51256. */
  51257. Animation.prototype._getKeyValue = function (value) {
  51258. if (typeof value === "function") {
  51259. return value();
  51260. }
  51261. return value;
  51262. };
  51263. /**
  51264. * @hidden Internal use only
  51265. */
  51266. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51267. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51268. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51269. }
  51270. var keys = this.getKeys();
  51271. // Try to get a hash to find the right key
  51272. 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));
  51273. if (keys[startKeyIndex].frame >= currentFrame) {
  51274. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51275. startKeyIndex--;
  51276. }
  51277. }
  51278. for (var key = startKeyIndex; key < keys.length; key++) {
  51279. var endKey = keys[key + 1];
  51280. if (endKey.frame >= currentFrame) {
  51281. var startKey = keys[key];
  51282. var startValue = this._getKeyValue(startKey.value);
  51283. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51284. return startValue;
  51285. }
  51286. var endValue = this._getKeyValue(endKey.value);
  51287. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51288. var frameDelta = endKey.frame - startKey.frame;
  51289. // gradient : percent of currentFrame between the frame inf and the frame sup
  51290. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51291. // check for easingFunction and correction of gradient
  51292. var easingFunction = this.getEasingFunction();
  51293. if (easingFunction != null) {
  51294. gradient = easingFunction.ease(gradient);
  51295. }
  51296. switch (this.dataType) {
  51297. // Float
  51298. case Animation.ANIMATIONTYPE_FLOAT:
  51299. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51300. switch (loopMode) {
  51301. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51302. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51303. return floatValue;
  51304. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51305. return offsetValue * repeatCount + floatValue;
  51306. }
  51307. break;
  51308. // Quaternion
  51309. case Animation.ANIMATIONTYPE_QUATERNION:
  51310. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51311. switch (loopMode) {
  51312. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51313. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51314. return quatValue;
  51315. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51316. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51317. }
  51318. return quatValue;
  51319. // Vector3
  51320. case Animation.ANIMATIONTYPE_VECTOR3:
  51321. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51322. switch (loopMode) {
  51323. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51324. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51325. return vec3Value;
  51326. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51327. return vec3Value.add(offsetValue.scale(repeatCount));
  51328. }
  51329. // Vector2
  51330. case Animation.ANIMATIONTYPE_VECTOR2:
  51331. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51332. switch (loopMode) {
  51333. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51334. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51335. return vec2Value;
  51336. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51337. return vec2Value.add(offsetValue.scale(repeatCount));
  51338. }
  51339. // Size
  51340. case Animation.ANIMATIONTYPE_SIZE:
  51341. switch (loopMode) {
  51342. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51343. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51344. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51345. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51346. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51347. }
  51348. // Color3
  51349. case Animation.ANIMATIONTYPE_COLOR3:
  51350. switch (loopMode) {
  51351. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51352. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51353. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51354. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51355. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51356. }
  51357. // Matrix
  51358. case Animation.ANIMATIONTYPE_MATRIX:
  51359. switch (loopMode) {
  51360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51362. if (Animation.AllowMatricesInterpolation) {
  51363. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51364. }
  51365. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51366. return startValue;
  51367. }
  51368. default:
  51369. break;
  51370. }
  51371. break;
  51372. }
  51373. }
  51374. return this._getKeyValue(keys[keys.length - 1].value);
  51375. };
  51376. /**
  51377. * Defines the function to use to interpolate matrices
  51378. * @param startValue defines the start matrix
  51379. * @param endValue defines the end matrix
  51380. * @param gradient defines the gradient between both matrices
  51381. * @param result defines an optional target matrix where to store the interpolation
  51382. * @returns the interpolated matrix
  51383. */
  51384. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51385. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51386. if (result) {
  51387. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51388. return result;
  51389. }
  51390. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51391. }
  51392. if (result) {
  51393. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51394. return result;
  51395. }
  51396. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51397. };
  51398. /**
  51399. * Makes a copy of the animation
  51400. * @returns Cloned animation
  51401. */
  51402. Animation.prototype.clone = function () {
  51403. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51404. clone.enableBlending = this.enableBlending;
  51405. clone.blendingSpeed = this.blendingSpeed;
  51406. if (this._keys) {
  51407. clone.setKeys(this._keys);
  51408. }
  51409. if (this._ranges) {
  51410. clone._ranges = {};
  51411. for (var name in this._ranges) {
  51412. var range = this._ranges[name];
  51413. if (!range) {
  51414. continue;
  51415. }
  51416. clone._ranges[name] = range.clone();
  51417. }
  51418. }
  51419. return clone;
  51420. };
  51421. /**
  51422. * Sets the key frames of the animation
  51423. * @param values The animation key frames to set
  51424. */
  51425. Animation.prototype.setKeys = function (values) {
  51426. this._keys = values.slice(0);
  51427. };
  51428. /**
  51429. * Serializes the animation to an object
  51430. * @returns Serialized object
  51431. */
  51432. Animation.prototype.serialize = function () {
  51433. var serializationObject = {};
  51434. serializationObject.name = this.name;
  51435. serializationObject.property = this.targetProperty;
  51436. serializationObject.framePerSecond = this.framePerSecond;
  51437. serializationObject.dataType = this.dataType;
  51438. serializationObject.loopBehavior = this.loopMode;
  51439. serializationObject.enableBlending = this.enableBlending;
  51440. serializationObject.blendingSpeed = this.blendingSpeed;
  51441. var dataType = this.dataType;
  51442. serializationObject.keys = [];
  51443. var keys = this.getKeys();
  51444. for (var index = 0; index < keys.length; index++) {
  51445. var animationKey = keys[index];
  51446. var key = {};
  51447. key.frame = animationKey.frame;
  51448. switch (dataType) {
  51449. case Animation.ANIMATIONTYPE_FLOAT:
  51450. key.values = [animationKey.value];
  51451. break;
  51452. case Animation.ANIMATIONTYPE_QUATERNION:
  51453. case Animation.ANIMATIONTYPE_MATRIX:
  51454. case Animation.ANIMATIONTYPE_VECTOR3:
  51455. case Animation.ANIMATIONTYPE_COLOR3:
  51456. key.values = animationKey.value.asArray();
  51457. break;
  51458. }
  51459. serializationObject.keys.push(key);
  51460. }
  51461. serializationObject.ranges = [];
  51462. for (var name in this._ranges) {
  51463. var source = this._ranges[name];
  51464. if (!source) {
  51465. continue;
  51466. }
  51467. var range = {};
  51468. range.name = name;
  51469. range.from = source.from;
  51470. range.to = source.to;
  51471. serializationObject.ranges.push(range);
  51472. }
  51473. return serializationObject;
  51474. };
  51475. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51476. /**
  51477. * Get the float animation type
  51478. */
  51479. get: function () {
  51480. return Animation._ANIMATIONTYPE_FLOAT;
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51486. /**
  51487. * Get the Vector3 animation type
  51488. */
  51489. get: function () {
  51490. return Animation._ANIMATIONTYPE_VECTOR3;
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51496. /**
  51497. * Get the Vectpr2 animation type
  51498. */
  51499. get: function () {
  51500. return Animation._ANIMATIONTYPE_VECTOR2;
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51506. /**
  51507. * Get the Size animation type
  51508. */
  51509. get: function () {
  51510. return Animation._ANIMATIONTYPE_SIZE;
  51511. },
  51512. enumerable: true,
  51513. configurable: true
  51514. });
  51515. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51516. /**
  51517. * Get the Quaternion animation type
  51518. */
  51519. get: function () {
  51520. return Animation._ANIMATIONTYPE_QUATERNION;
  51521. },
  51522. enumerable: true,
  51523. configurable: true
  51524. });
  51525. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51526. /**
  51527. * Get the Matrix animation type
  51528. */
  51529. get: function () {
  51530. return Animation._ANIMATIONTYPE_MATRIX;
  51531. },
  51532. enumerable: true,
  51533. configurable: true
  51534. });
  51535. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51536. /**
  51537. * Get the Color3 animation type
  51538. */
  51539. get: function () {
  51540. return Animation._ANIMATIONTYPE_COLOR3;
  51541. },
  51542. enumerable: true,
  51543. configurable: true
  51544. });
  51545. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51546. /**
  51547. * Get the Relative Loop Mode
  51548. */
  51549. get: function () {
  51550. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51551. },
  51552. enumerable: true,
  51553. configurable: true
  51554. });
  51555. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51556. /**
  51557. * Get the Cycle Loop Mode
  51558. */
  51559. get: function () {
  51560. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51561. },
  51562. enumerable: true,
  51563. configurable: true
  51564. });
  51565. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51566. /**
  51567. * Get the Constant Loop Mode
  51568. */
  51569. get: function () {
  51570. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51571. },
  51572. enumerable: true,
  51573. configurable: true
  51574. });
  51575. /** @hidden */
  51576. Animation._UniversalLerp = function (left, right, amount) {
  51577. var constructor = left.constructor;
  51578. if (constructor.Lerp) { // Lerp supported
  51579. return constructor.Lerp(left, right, amount);
  51580. }
  51581. else if (constructor.Slerp) { // Slerp supported
  51582. return constructor.Slerp(left, right, amount);
  51583. }
  51584. else if (left.toFixed) { // Number
  51585. return left * (1.0 - amount) + amount * right;
  51586. }
  51587. else { // Blending not supported
  51588. return right;
  51589. }
  51590. };
  51591. /**
  51592. * Parses an animation object and creates an animation
  51593. * @param parsedAnimation Parsed animation object
  51594. * @returns Animation object
  51595. */
  51596. Animation.Parse = function (parsedAnimation) {
  51597. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51598. var dataType = parsedAnimation.dataType;
  51599. var keys = [];
  51600. var data;
  51601. var index;
  51602. if (parsedAnimation.enableBlending) {
  51603. animation.enableBlending = parsedAnimation.enableBlending;
  51604. }
  51605. if (parsedAnimation.blendingSpeed) {
  51606. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51607. }
  51608. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51609. var key = parsedAnimation.keys[index];
  51610. var inTangent;
  51611. var outTangent;
  51612. switch (dataType) {
  51613. case Animation.ANIMATIONTYPE_FLOAT:
  51614. data = key.values[0];
  51615. if (key.values.length >= 1) {
  51616. inTangent = key.values[1];
  51617. }
  51618. if (key.values.length >= 2) {
  51619. outTangent = key.values[2];
  51620. }
  51621. break;
  51622. case Animation.ANIMATIONTYPE_QUATERNION:
  51623. data = BABYLON.Quaternion.FromArray(key.values);
  51624. if (key.values.length >= 8) {
  51625. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51626. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51627. inTangent = _inTangent;
  51628. }
  51629. }
  51630. if (key.values.length >= 12) {
  51631. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51632. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51633. outTangent = _outTangent;
  51634. }
  51635. }
  51636. break;
  51637. case Animation.ANIMATIONTYPE_MATRIX:
  51638. data = BABYLON.Matrix.FromArray(key.values);
  51639. break;
  51640. case Animation.ANIMATIONTYPE_COLOR3:
  51641. data = BABYLON.Color3.FromArray(key.values);
  51642. break;
  51643. case Animation.ANIMATIONTYPE_VECTOR3:
  51644. default:
  51645. data = BABYLON.Vector3.FromArray(key.values);
  51646. break;
  51647. }
  51648. var keyData = {};
  51649. keyData.frame = key.frame;
  51650. keyData.value = data;
  51651. if (inTangent != undefined) {
  51652. keyData.inTangent = inTangent;
  51653. }
  51654. if (outTangent != undefined) {
  51655. keyData.outTangent = outTangent;
  51656. }
  51657. keys.push(keyData);
  51658. }
  51659. animation.setKeys(keys);
  51660. if (parsedAnimation.ranges) {
  51661. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51662. data = parsedAnimation.ranges[index];
  51663. animation.createRange(data.name, data.from, data.to);
  51664. }
  51665. }
  51666. return animation;
  51667. };
  51668. /**
  51669. * Appends the serialized animations from the source animations
  51670. * @param source Source containing the animations
  51671. * @param destination Target to store the animations
  51672. */
  51673. Animation.AppendSerializedAnimations = function (source, destination) {
  51674. if (source.animations) {
  51675. destination.animations = [];
  51676. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51677. var animation = source.animations[animationIndex];
  51678. destination.animations.push(animation.serialize());
  51679. }
  51680. }
  51681. };
  51682. /**
  51683. * Use matrix interpolation instead of using direct key value when animating matrices
  51684. */
  51685. Animation.AllowMatricesInterpolation = false;
  51686. /**
  51687. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51688. */
  51689. Animation.AllowMatrixDecomposeForInterpolation = true;
  51690. // Statics
  51691. /**
  51692. * Float animation type
  51693. */
  51694. Animation._ANIMATIONTYPE_FLOAT = 0;
  51695. /**
  51696. * Vector3 animation type
  51697. */
  51698. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51699. /**
  51700. * Quaternion animation type
  51701. */
  51702. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51703. /**
  51704. * Matrix animation type
  51705. */
  51706. Animation._ANIMATIONTYPE_MATRIX = 3;
  51707. /**
  51708. * Color3 animation type
  51709. */
  51710. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51711. /**
  51712. * Vector2 animation type
  51713. */
  51714. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51715. /**
  51716. * Size animation type
  51717. */
  51718. Animation._ANIMATIONTYPE_SIZE = 6;
  51719. /**
  51720. * Relative Loop Mode
  51721. */
  51722. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51723. /**
  51724. * Cycle Loop Mode
  51725. */
  51726. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51727. /**
  51728. * Constant Loop Mode
  51729. */
  51730. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51731. return Animation;
  51732. }());
  51733. BABYLON.Animation = Animation;
  51734. })(BABYLON || (BABYLON = {}));
  51735. //# sourceMappingURL=babylon.animation.js.map
  51736. var BABYLON;
  51737. (function (BABYLON) {
  51738. /**
  51739. * This class defines the direct association between an animation and a target
  51740. */
  51741. var TargetedAnimation = /** @class */ (function () {
  51742. function TargetedAnimation() {
  51743. }
  51744. return TargetedAnimation;
  51745. }());
  51746. BABYLON.TargetedAnimation = TargetedAnimation;
  51747. /**
  51748. * Use this class to create coordinated animations on multiple targets
  51749. */
  51750. var AnimationGroup = /** @class */ (function () {
  51751. function AnimationGroup(name, scene) {
  51752. if (scene === void 0) { scene = null; }
  51753. this.name = name;
  51754. this._targetedAnimations = new Array();
  51755. this._animatables = new Array();
  51756. this._from = Number.MAX_VALUE;
  51757. this._to = -Number.MAX_VALUE;
  51758. this._speedRatio = 1;
  51759. this.onAnimationEndObservable = new BABYLON.Observable();
  51760. /**
  51761. * This observable will notify when all animations have ended.
  51762. */
  51763. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51764. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51765. this._scene.animationGroups.push(this);
  51766. }
  51767. Object.defineProperty(AnimationGroup.prototype, "from", {
  51768. /**
  51769. * Gets the first frame
  51770. */
  51771. get: function () {
  51772. return this._from;
  51773. },
  51774. enumerable: true,
  51775. configurable: true
  51776. });
  51777. Object.defineProperty(AnimationGroup.prototype, "to", {
  51778. /**
  51779. * Gets the last frame
  51780. */
  51781. get: function () {
  51782. return this._to;
  51783. },
  51784. enumerable: true,
  51785. configurable: true
  51786. });
  51787. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51788. /**
  51789. * Define if the animations are started
  51790. */
  51791. get: function () {
  51792. return this._isStarted;
  51793. },
  51794. enumerable: true,
  51795. configurable: true
  51796. });
  51797. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51798. /**
  51799. * Gets or sets the speed ratio to use for all animations
  51800. */
  51801. get: function () {
  51802. return this._speedRatio;
  51803. },
  51804. /**
  51805. * Gets or sets the speed ratio to use for all animations
  51806. */
  51807. set: function (value) {
  51808. if (this._speedRatio === value) {
  51809. return;
  51810. }
  51811. this._speedRatio = value;
  51812. for (var index = 0; index < this._animatables.length; index++) {
  51813. var animatable = this._animatables[index];
  51814. animatable.speedRatio = this._speedRatio;
  51815. }
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51821. /**
  51822. * Gets the targeted animations for this animation group
  51823. */
  51824. get: function () {
  51825. return this._targetedAnimations;
  51826. },
  51827. enumerable: true,
  51828. configurable: true
  51829. });
  51830. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51831. /**
  51832. * returning the list of animatables controlled by this animation group.
  51833. */
  51834. get: function () {
  51835. return this._animatables;
  51836. },
  51837. enumerable: true,
  51838. configurable: true
  51839. });
  51840. /**
  51841. * Add an animation (with its target) in the group
  51842. * @param animation defines the animation we want to add
  51843. * @param target defines the target of the animation
  51844. * @returns the {BABYLON.TargetedAnimation} object
  51845. */
  51846. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51847. var targetedAnimation = {
  51848. animation: animation,
  51849. target: target
  51850. };
  51851. var keys = animation.getKeys();
  51852. if (this._from > keys[0].frame) {
  51853. this._from = keys[0].frame;
  51854. }
  51855. if (this._to < keys[keys.length - 1].frame) {
  51856. this._to = keys[keys.length - 1].frame;
  51857. }
  51858. this._targetedAnimations.push(targetedAnimation);
  51859. return targetedAnimation;
  51860. };
  51861. /**
  51862. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51863. * It can add constant keys at begin or end
  51864. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51865. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51866. */
  51867. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51868. if (beginFrame === void 0) { beginFrame = null; }
  51869. if (endFrame === void 0) { endFrame = null; }
  51870. if (beginFrame == null)
  51871. beginFrame = this._from;
  51872. if (endFrame == null)
  51873. endFrame = this._to;
  51874. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51875. var targetedAnimation = this._targetedAnimations[index];
  51876. var keys = targetedAnimation.animation.getKeys();
  51877. var startKey = keys[0];
  51878. var endKey = keys[keys.length - 1];
  51879. if (startKey.frame > beginFrame) {
  51880. var newKey = {
  51881. frame: beginFrame,
  51882. value: startKey.value,
  51883. inTangent: startKey.inTangent,
  51884. outTangent: startKey.outTangent,
  51885. interpolation: startKey.interpolation
  51886. };
  51887. keys.splice(0, 0, newKey);
  51888. }
  51889. if (endKey.frame < endFrame) {
  51890. var newKey = {
  51891. frame: endFrame,
  51892. value: endKey.value,
  51893. inTangent: endKey.outTangent,
  51894. outTangent: endKey.outTangent,
  51895. interpolation: endKey.interpolation
  51896. };
  51897. keys.push(newKey);
  51898. }
  51899. }
  51900. this._from = beginFrame;
  51901. this._to = endFrame;
  51902. return this;
  51903. };
  51904. /**
  51905. * Start all animations on given targets
  51906. * @param loop defines if animations must loop
  51907. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51908. * @param from defines the from key (optional)
  51909. * @param to defines the to key (optional)
  51910. * @returns the current animation group
  51911. */
  51912. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51913. var _this = this;
  51914. if (loop === void 0) { loop = false; }
  51915. if (speedRatio === void 0) { speedRatio = 1; }
  51916. if (this._isStarted || this._targetedAnimations.length === 0) {
  51917. return this;
  51918. }
  51919. var _loop_1 = function (targetedAnimation) {
  51920. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51921. animatable.onAnimationEnd = function () {
  51922. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51923. _this._checkAnimationGroupEnded(animatable);
  51924. };
  51925. this_1._animatables.push(animatable);
  51926. };
  51927. var this_1 = this;
  51928. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51929. var targetedAnimation = _a[_i];
  51930. _loop_1(targetedAnimation);
  51931. }
  51932. this._speedRatio = speedRatio;
  51933. this._isStarted = true;
  51934. return this;
  51935. };
  51936. /**
  51937. * Pause all animations
  51938. */
  51939. AnimationGroup.prototype.pause = function () {
  51940. if (!this._isStarted) {
  51941. return this;
  51942. }
  51943. for (var index = 0; index < this._animatables.length; index++) {
  51944. var animatable = this._animatables[index];
  51945. animatable.pause();
  51946. }
  51947. return this;
  51948. };
  51949. /**
  51950. * Play all animations to initial state
  51951. * This function will start() the animations if they were not started or will restart() them if they were paused
  51952. * @param loop defines if animations must loop
  51953. */
  51954. AnimationGroup.prototype.play = function (loop) {
  51955. // only if all animatables are ready and exist
  51956. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51957. if (loop !== undefined) {
  51958. for (var index = 0; index < this._animatables.length; index++) {
  51959. var animatable = this._animatables[index];
  51960. animatable.loopAnimation = loop;
  51961. }
  51962. }
  51963. this.restart();
  51964. }
  51965. else {
  51966. this.stop();
  51967. this.start(loop, this._speedRatio);
  51968. }
  51969. return this;
  51970. };
  51971. /**
  51972. * Reset all animations to initial state
  51973. */
  51974. AnimationGroup.prototype.reset = function () {
  51975. if (!this._isStarted) {
  51976. return this;
  51977. }
  51978. for (var index = 0; index < this._animatables.length; index++) {
  51979. var animatable = this._animatables[index];
  51980. animatable.reset();
  51981. }
  51982. return this;
  51983. };
  51984. /**
  51985. * Restart animations from key 0
  51986. */
  51987. AnimationGroup.prototype.restart = function () {
  51988. if (!this._isStarted) {
  51989. return this;
  51990. }
  51991. for (var index = 0; index < this._animatables.length; index++) {
  51992. var animatable = this._animatables[index];
  51993. animatable.restart();
  51994. }
  51995. return this;
  51996. };
  51997. /**
  51998. * Stop all animations
  51999. */
  52000. AnimationGroup.prototype.stop = function () {
  52001. if (!this._isStarted) {
  52002. return this;
  52003. }
  52004. for (var index = 0; index < this._animatables.length; index++) {
  52005. var animatable = this._animatables[index];
  52006. animatable.stop();
  52007. }
  52008. this._isStarted = false;
  52009. return this;
  52010. };
  52011. /**
  52012. * Set animation weight for all animatables
  52013. * @param weight defines the weight to use
  52014. * @return the animationGroup
  52015. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52016. */
  52017. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52018. for (var index = 0; index < this._animatables.length; index++) {
  52019. var animatable = this._animatables[index];
  52020. animatable.weight = weight;
  52021. }
  52022. return this;
  52023. };
  52024. /**
  52025. * Synchronize and normalize all animatables with a source animatable
  52026. * @param root defines the root animatable to synchronize with
  52027. * @return the animationGroup
  52028. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52029. */
  52030. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52031. for (var index = 0; index < this._animatables.length; index++) {
  52032. var animatable = this._animatables[index];
  52033. animatable.syncWith(root);
  52034. }
  52035. return this;
  52036. };
  52037. /**
  52038. * Goes to a specific frame in this animation group
  52039. * @param frame the frame number to go to
  52040. * @return the animationGroup
  52041. */
  52042. AnimationGroup.prototype.goToFrame = function (frame) {
  52043. if (!this._isStarted) {
  52044. return this;
  52045. }
  52046. for (var index = 0; index < this._animatables.length; index++) {
  52047. var animatable = this._animatables[index];
  52048. animatable.goToFrame(frame);
  52049. }
  52050. return this;
  52051. };
  52052. /**
  52053. * Dispose all associated resources
  52054. */
  52055. AnimationGroup.prototype.dispose = function () {
  52056. this._targetedAnimations = [];
  52057. this._animatables = [];
  52058. var index = this._scene.animationGroups.indexOf(this);
  52059. if (index > -1) {
  52060. this._scene.animationGroups.splice(index, 1);
  52061. }
  52062. };
  52063. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52064. // animatable should be taken out of the array
  52065. var idx = this._animatables.indexOf(animatable);
  52066. if (idx > -1) {
  52067. this._animatables.splice(idx, 1);
  52068. }
  52069. // all animatables were removed? animation group ended!
  52070. if (this._animatables.length === 0) {
  52071. this._isStarted = false;
  52072. this.onAnimationGroupEndObservable.notifyObservers(this);
  52073. }
  52074. };
  52075. return AnimationGroup;
  52076. }());
  52077. BABYLON.AnimationGroup = AnimationGroup;
  52078. })(BABYLON || (BABYLON = {}));
  52079. //# sourceMappingURL=babylon.animationGroup.js.map
  52080. var BABYLON;
  52081. (function (BABYLON) {
  52082. /**
  52083. * Defines a runtime animation
  52084. */
  52085. var RuntimeAnimation = /** @class */ (function () {
  52086. /**
  52087. * Create a new RuntimeAnimation object
  52088. * @param target defines the target of the animation
  52089. * @param animation defines the source animation object
  52090. * @param scene defines the hosting scene
  52091. * @param host defines the initiating Animatable
  52092. */
  52093. function RuntimeAnimation(target, animation, scene, host) {
  52094. var _this = this;
  52095. this._events = new Array();
  52096. /**
  52097. * The current frame of the runtime animation
  52098. */
  52099. this._currentFrame = 0;
  52100. /**
  52101. * The original value of the runtime animation
  52102. */
  52103. this._originalValue = new Array();
  52104. /**
  52105. * The offsets cache of the runtime animation
  52106. */
  52107. this._offsetsCache = {};
  52108. /**
  52109. * The high limits cache of the runtime animation
  52110. */
  52111. this._highLimitsCache = {};
  52112. /**
  52113. * Specifies if the runtime animation has been stopped
  52114. */
  52115. this._stopped = false;
  52116. /**
  52117. * The blending factor of the runtime animation
  52118. */
  52119. this._blendingFactor = 0;
  52120. /**
  52121. * The target path of the runtime animation
  52122. */
  52123. this._targetPath = "";
  52124. /**
  52125. * The weight of the runtime animation
  52126. */
  52127. this._weight = 1.0;
  52128. /**
  52129. * The ratio offset of the runtime animation
  52130. */
  52131. this._ratioOffset = 0;
  52132. /**
  52133. * The previous delay of the runtime animation
  52134. */
  52135. this._previousDelay = 0;
  52136. /**
  52137. * The previous ratio of the runtime animation
  52138. */
  52139. this._previousRatio = 0;
  52140. this._animation = animation;
  52141. this._target = target;
  52142. this._scene = scene;
  52143. this._host = host;
  52144. animation._runtimeAnimations.push(this);
  52145. // Cloning events locally
  52146. var events = animation.getEvents();
  52147. if (events && events.length > 0) {
  52148. events.forEach(function (e) {
  52149. _this._events.push(e._clone());
  52150. });
  52151. }
  52152. }
  52153. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52154. /**
  52155. * Gets the current frame of the runtime animation
  52156. */
  52157. get: function () {
  52158. return this._currentFrame;
  52159. },
  52160. enumerable: true,
  52161. configurable: true
  52162. });
  52163. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52164. /**
  52165. * Gets the weight of the runtime animation
  52166. */
  52167. get: function () {
  52168. return this._weight;
  52169. },
  52170. enumerable: true,
  52171. configurable: true
  52172. });
  52173. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52174. /**
  52175. * Gets the current value of the runtime animation
  52176. */
  52177. get: function () {
  52178. return this._currentValue;
  52179. },
  52180. enumerable: true,
  52181. configurable: true
  52182. });
  52183. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52184. /**
  52185. * Gets the target path of the runtime animation
  52186. */
  52187. get: function () {
  52188. return this._targetPath;
  52189. },
  52190. enumerable: true,
  52191. configurable: true
  52192. });
  52193. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52194. /**
  52195. * Gets the actual target of the runtime animation
  52196. */
  52197. get: function () {
  52198. return this._activeTarget;
  52199. },
  52200. enumerable: true,
  52201. configurable: true
  52202. });
  52203. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52204. /**
  52205. * Gets the animation from the runtime animation
  52206. */
  52207. get: function () {
  52208. return this._animation;
  52209. },
  52210. enumerable: true,
  52211. configurable: true
  52212. });
  52213. /**
  52214. * Resets the runtime animation to the beginning
  52215. * @param restoreOriginal defines whether to restore the target property to the original value
  52216. */
  52217. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52218. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52219. if (restoreOriginal) {
  52220. if (this._target instanceof Array) {
  52221. var index = 0;
  52222. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52223. var target = _a[_i];
  52224. if (this._originalValue[index] !== undefined) {
  52225. this._setValue(target, this._originalValue[index], -1);
  52226. }
  52227. index++;
  52228. }
  52229. }
  52230. else {
  52231. if (this._originalValue[0] !== undefined) {
  52232. this._setValue(this._target, this._originalValue[0], -1);
  52233. }
  52234. }
  52235. }
  52236. this._offsetsCache = {};
  52237. this._highLimitsCache = {};
  52238. this._currentFrame = 0;
  52239. this._blendingFactor = 0;
  52240. this._originalValue = new Array();
  52241. // Events
  52242. for (var index = 0; index < this._events.length; index++) {
  52243. this._events[index].isDone = false;
  52244. }
  52245. };
  52246. /**
  52247. * Specifies if the runtime animation is stopped
  52248. * @returns Boolean specifying if the runtime animation is stopped
  52249. */
  52250. RuntimeAnimation.prototype.isStopped = function () {
  52251. return this._stopped;
  52252. };
  52253. /**
  52254. * Disposes of the runtime animation
  52255. */
  52256. RuntimeAnimation.prototype.dispose = function () {
  52257. var index = this._animation.runtimeAnimations.indexOf(this);
  52258. if (index > -1) {
  52259. this._animation.runtimeAnimations.splice(index, 1);
  52260. }
  52261. };
  52262. /**
  52263. * Interpolates the animation from the current frame
  52264. * @param currentFrame The frame to interpolate the animation to
  52265. * @param repeatCount The number of times that the animation should loop
  52266. * @param loopMode The type of looping mode to use
  52267. * @param offsetValue Animation offset value
  52268. * @param highLimitValue The high limit value
  52269. * @returns The interpolated value
  52270. */
  52271. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52272. this._currentFrame = currentFrame;
  52273. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52274. this._workValue = BABYLON.Matrix.Zero();
  52275. }
  52276. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52277. };
  52278. /**
  52279. * Apply the interpolated value to the target
  52280. * @param currentValue defines the value computed by the animation
  52281. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52282. */
  52283. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52284. if (weight === void 0) { weight = 1.0; }
  52285. if (this._target instanceof Array) {
  52286. var index = 0;
  52287. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52288. var target = _a[_i];
  52289. this._setValue(target, currentValue, weight, index);
  52290. index++;
  52291. }
  52292. }
  52293. else {
  52294. this._setValue(this._target, currentValue, weight);
  52295. }
  52296. };
  52297. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52298. if (targetIndex === void 0) { targetIndex = 0; }
  52299. // Set value
  52300. var path;
  52301. var destination;
  52302. var targetPropertyPath = this._animation.targetPropertyPath;
  52303. if (targetPropertyPath.length > 1) {
  52304. var property = target[targetPropertyPath[0]];
  52305. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52306. property = property[targetPropertyPath[index]];
  52307. }
  52308. path = targetPropertyPath[targetPropertyPath.length - 1];
  52309. destination = property;
  52310. }
  52311. else {
  52312. path = targetPropertyPath[0];
  52313. destination = target;
  52314. }
  52315. this._targetPath = path;
  52316. this._activeTarget = destination;
  52317. this._weight = weight;
  52318. if (this._originalValue[targetIndex] === undefined) {
  52319. var originalValue = void 0;
  52320. if (destination.getRestPose && path === "_matrix") { // For bones
  52321. originalValue = destination.getRestPose();
  52322. }
  52323. else {
  52324. originalValue = destination[path];
  52325. }
  52326. if (originalValue && originalValue.clone) {
  52327. this._originalValue[targetIndex] = originalValue.clone();
  52328. }
  52329. else {
  52330. this._originalValue[targetIndex] = originalValue;
  52331. }
  52332. }
  52333. // Blending
  52334. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52335. if (enableBlending && this._blendingFactor <= 1.0) {
  52336. if (!this._originalBlendValue) {
  52337. var originalValue = destination[path];
  52338. if (originalValue.clone) {
  52339. this._originalBlendValue = originalValue.clone();
  52340. }
  52341. else {
  52342. this._originalBlendValue = originalValue;
  52343. }
  52344. }
  52345. if (this._originalBlendValue.m) { // Matrix
  52346. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52347. if (this._currentValue) {
  52348. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52349. }
  52350. else {
  52351. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52352. }
  52353. }
  52354. else {
  52355. if (this._currentValue) {
  52356. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52357. }
  52358. else {
  52359. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52360. }
  52361. }
  52362. }
  52363. else {
  52364. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52365. }
  52366. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52367. this._blendingFactor += blendingSpeed;
  52368. }
  52369. else {
  52370. this._currentValue = currentValue;
  52371. }
  52372. if (weight !== -1.0) {
  52373. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52374. }
  52375. else {
  52376. destination[path] = this._currentValue;
  52377. }
  52378. if (target.markAsDirty) {
  52379. target.markAsDirty(this._animation.targetProperty);
  52380. }
  52381. };
  52382. /**
  52383. * Gets the loop pmode of the runtime animation
  52384. * @returns Loop Mode
  52385. */
  52386. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52387. if (this._target && this._target.animationPropertiesOverride) {
  52388. return this._target.animationPropertiesOverride.loopMode;
  52389. }
  52390. return this._animation.loopMode;
  52391. };
  52392. /**
  52393. * Move the current animation to a given frame
  52394. * @param frame defines the frame to move to
  52395. */
  52396. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52397. var keys = this._animation.getKeys();
  52398. if (frame < keys[0].frame) {
  52399. frame = keys[0].frame;
  52400. }
  52401. else if (frame > keys[keys.length - 1].frame) {
  52402. frame = keys[keys.length - 1].frame;
  52403. }
  52404. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52405. this.setValue(currentValue, -1);
  52406. };
  52407. /**
  52408. * @hidden Internal use only
  52409. */
  52410. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52411. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52412. this._ratioOffset = this._previousRatio - newRatio;
  52413. };
  52414. /**
  52415. * Execute the current animation
  52416. * @param delay defines the delay to add to the current frame
  52417. * @param from defines the lower bound of the animation range
  52418. * @param to defines the upper bound of the animation range
  52419. * @param loop defines if the current animation must loop
  52420. * @param speedRatio defines the current speed ratio
  52421. * @param weight defines the weight of the animation (default is -1 so no weight)
  52422. * @returns a boolean indicating if the animation has ended
  52423. */
  52424. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52425. if (weight === void 0) { weight = -1.0; }
  52426. var targetPropertyPath = this._animation.targetPropertyPath;
  52427. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52428. this._stopped = true;
  52429. return false;
  52430. }
  52431. var returnValue = true;
  52432. var keys = this._animation.getKeys();
  52433. // Adding a start key at frame 0 if missing
  52434. if (keys[0].frame !== 0) {
  52435. var newKey = { frame: 0, value: keys[0].value };
  52436. keys.splice(0, 0, newKey);
  52437. }
  52438. // Check limits
  52439. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52440. from = keys[0].frame;
  52441. }
  52442. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52443. to = keys[keys.length - 1].frame;
  52444. }
  52445. //to and from cannot be the same key
  52446. if (from === to) {
  52447. if (from > keys[0].frame) {
  52448. from--;
  52449. }
  52450. else if (to < keys[keys.length - 1].frame) {
  52451. to++;
  52452. }
  52453. }
  52454. // Compute ratio
  52455. var range = to - from;
  52456. var offsetValue;
  52457. // ratio represents the frame delta between from and to
  52458. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52459. var highLimitValue = 0;
  52460. this._previousDelay = delay;
  52461. this._previousRatio = ratio;
  52462. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52463. returnValue = false;
  52464. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52465. }
  52466. else {
  52467. // Get max value if required
  52468. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52469. var keyOffset = to.toString() + from.toString();
  52470. if (!this._offsetsCache[keyOffset]) {
  52471. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52472. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52473. switch (this._animation.dataType) {
  52474. // Float
  52475. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52476. this._offsetsCache[keyOffset] = toValue - fromValue;
  52477. break;
  52478. // Quaternion
  52479. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52480. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52481. break;
  52482. // Vector3
  52483. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52484. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52485. // Vector2
  52486. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52487. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52488. // Size
  52489. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52490. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52491. // Color3
  52492. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52493. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52494. default:
  52495. break;
  52496. }
  52497. this._highLimitsCache[keyOffset] = toValue;
  52498. }
  52499. highLimitValue = this._highLimitsCache[keyOffset];
  52500. offsetValue = this._offsetsCache[keyOffset];
  52501. }
  52502. }
  52503. if (offsetValue === undefined) {
  52504. switch (this._animation.dataType) {
  52505. // Float
  52506. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52507. offsetValue = 0;
  52508. break;
  52509. // Quaternion
  52510. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52511. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52512. break;
  52513. // Vector3
  52514. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52515. offsetValue = BABYLON.Vector3.Zero();
  52516. break;
  52517. // Vector2
  52518. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52519. offsetValue = BABYLON.Vector2.Zero();
  52520. break;
  52521. // Size
  52522. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52523. offsetValue = BABYLON.Size.Zero();
  52524. break;
  52525. // Color3
  52526. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52527. offsetValue = BABYLON.Color3.Black();
  52528. }
  52529. }
  52530. // Compute value
  52531. var repeatCount = (ratio / range) >> 0;
  52532. var currentFrame = returnValue ? from + ratio % range : to;
  52533. // Need to normalize?
  52534. if (this._host && this._host.syncRoot) {
  52535. var syncRoot = this._host.syncRoot;
  52536. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52537. currentFrame = from + (to - from) * hostNormalizedFrame;
  52538. }
  52539. // Reset events if looping
  52540. var events = this._events;
  52541. if (range > 0 && this.currentFrame > currentFrame ||
  52542. range < 0 && this.currentFrame < currentFrame) {
  52543. // Need to reset animation events
  52544. for (var index = 0; index < events.length; index++) {
  52545. if (!events[index].onlyOnce) {
  52546. // reset event, the animation is looping
  52547. events[index].isDone = false;
  52548. }
  52549. }
  52550. }
  52551. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52552. // Set value
  52553. this.setValue(currentValue, weight);
  52554. // Check events
  52555. for (var index = 0; index < events.length; index++) {
  52556. // Make sure current frame has passed event frame and that event frame is within the current range
  52557. // Also, handle both forward and reverse animations
  52558. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52559. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52560. var event = events[index];
  52561. if (!event.isDone) {
  52562. // If event should be done only once, remove it.
  52563. if (event.onlyOnce) {
  52564. events.splice(index, 1);
  52565. index--;
  52566. }
  52567. event.isDone = true;
  52568. event.action();
  52569. } // Don't do anything if the event has already be done.
  52570. }
  52571. }
  52572. if (!returnValue) {
  52573. this._stopped = true;
  52574. }
  52575. return returnValue;
  52576. };
  52577. return RuntimeAnimation;
  52578. }());
  52579. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52580. })(BABYLON || (BABYLON = {}));
  52581. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52582. var BABYLON;
  52583. (function (BABYLON) {
  52584. var Animatable = /** @class */ (function () {
  52585. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52586. if (fromFrame === void 0) { fromFrame = 0; }
  52587. if (toFrame === void 0) { toFrame = 100; }
  52588. if (loopAnimation === void 0) { loopAnimation = false; }
  52589. if (speedRatio === void 0) { speedRatio = 1.0; }
  52590. this.target = target;
  52591. this.fromFrame = fromFrame;
  52592. this.toFrame = toFrame;
  52593. this.loopAnimation = loopAnimation;
  52594. this.onAnimationEnd = onAnimationEnd;
  52595. this._localDelayOffset = null;
  52596. this._pausedDelay = null;
  52597. this._runtimeAnimations = new Array();
  52598. this._paused = false;
  52599. this._speedRatio = 1;
  52600. this._weight = -1.0;
  52601. this.animationStarted = false;
  52602. /**
  52603. * Observer raised when the animation ends
  52604. */
  52605. this.onAnimationEndObservable = new BABYLON.Observable();
  52606. this._scene = scene;
  52607. if (animations) {
  52608. this.appendAnimations(target, animations);
  52609. }
  52610. this._speedRatio = speedRatio;
  52611. scene._activeAnimatables.push(this);
  52612. }
  52613. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52614. /**
  52615. * Gets the root Animatable used to synchronize and normalize animations
  52616. */
  52617. get: function () {
  52618. return this._syncRoot;
  52619. },
  52620. enumerable: true,
  52621. configurable: true
  52622. });
  52623. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52624. /**
  52625. * Gets the current frame of the first RuntimeAnimation
  52626. * Used to synchronize Animatables
  52627. */
  52628. get: function () {
  52629. if (this._runtimeAnimations.length === 0) {
  52630. return 0;
  52631. }
  52632. return this._runtimeAnimations[0].currentFrame;
  52633. },
  52634. enumerable: true,
  52635. configurable: true
  52636. });
  52637. Object.defineProperty(Animatable.prototype, "weight", {
  52638. /**
  52639. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52640. */
  52641. get: function () {
  52642. return this._weight;
  52643. },
  52644. set: function (value) {
  52645. if (value === -1) { // -1 is ok and means no weight
  52646. this._weight = -1;
  52647. return;
  52648. }
  52649. // Else weight must be in [0, 1] range
  52650. this._weight = Math.min(Math.max(value, 0), 1.0);
  52651. },
  52652. enumerable: true,
  52653. configurable: true
  52654. });
  52655. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52656. /**
  52657. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52658. */
  52659. get: function () {
  52660. return this._speedRatio;
  52661. },
  52662. set: function (value) {
  52663. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52664. var animation = this._runtimeAnimations[index];
  52665. animation._prepareForSpeedRatioChange(value);
  52666. }
  52667. this._speedRatio = value;
  52668. },
  52669. enumerable: true,
  52670. configurable: true
  52671. });
  52672. // Methods
  52673. /**
  52674. * Synchronize and normalize current Animatable with a source Animatable
  52675. * This is useful when using animation weights and when animations are not of the same length
  52676. * @param root defines the root Animatable to synchronize with
  52677. * @returns the current Animatable
  52678. */
  52679. Animatable.prototype.syncWith = function (root) {
  52680. this._syncRoot = root;
  52681. if (root) {
  52682. // Make sure this animatable will animate after the root
  52683. var index = this._scene._activeAnimatables.indexOf(this);
  52684. if (index > -1) {
  52685. this._scene._activeAnimatables.splice(index, 1);
  52686. this._scene._activeAnimatables.push(this);
  52687. }
  52688. }
  52689. return this;
  52690. };
  52691. Animatable.prototype.getAnimations = function () {
  52692. return this._runtimeAnimations;
  52693. };
  52694. Animatable.prototype.appendAnimations = function (target, animations) {
  52695. for (var index = 0; index < animations.length; index++) {
  52696. var animation = animations[index];
  52697. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52698. }
  52699. };
  52700. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52701. var runtimeAnimations = this._runtimeAnimations;
  52702. for (var index = 0; index < runtimeAnimations.length; index++) {
  52703. if (runtimeAnimations[index].animation.targetProperty === property) {
  52704. return runtimeAnimations[index].animation;
  52705. }
  52706. }
  52707. return null;
  52708. };
  52709. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52710. var runtimeAnimations = this._runtimeAnimations;
  52711. for (var index = 0; index < runtimeAnimations.length; index++) {
  52712. if (runtimeAnimations[index].animation.targetProperty === property) {
  52713. return runtimeAnimations[index];
  52714. }
  52715. }
  52716. return null;
  52717. };
  52718. Animatable.prototype.reset = function () {
  52719. var runtimeAnimations = this._runtimeAnimations;
  52720. for (var index = 0; index < runtimeAnimations.length; index++) {
  52721. runtimeAnimations[index].reset(true);
  52722. }
  52723. this._localDelayOffset = null;
  52724. this._pausedDelay = null;
  52725. };
  52726. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52727. var runtimeAnimations = this._runtimeAnimations;
  52728. for (var index = 0; index < runtimeAnimations.length; index++) {
  52729. runtimeAnimations[index].animation.enableBlending = true;
  52730. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52731. }
  52732. };
  52733. Animatable.prototype.disableBlending = function () {
  52734. var runtimeAnimations = this._runtimeAnimations;
  52735. for (var index = 0; index < runtimeAnimations.length; index++) {
  52736. runtimeAnimations[index].animation.enableBlending = false;
  52737. }
  52738. };
  52739. Animatable.prototype.goToFrame = function (frame) {
  52740. var runtimeAnimations = this._runtimeAnimations;
  52741. if (runtimeAnimations[0]) {
  52742. var fps = runtimeAnimations[0].animation.framePerSecond;
  52743. var currentFrame = runtimeAnimations[0].currentFrame;
  52744. var adjustTime = frame - currentFrame;
  52745. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52746. if (this._localDelayOffset === null) {
  52747. this._localDelayOffset = 0;
  52748. }
  52749. this._localDelayOffset -= delay;
  52750. }
  52751. for (var index = 0; index < runtimeAnimations.length; index++) {
  52752. runtimeAnimations[index].goToFrame(frame);
  52753. }
  52754. };
  52755. Animatable.prototype.pause = function () {
  52756. if (this._paused) {
  52757. return;
  52758. }
  52759. this._paused = true;
  52760. };
  52761. Animatable.prototype.restart = function () {
  52762. this._paused = false;
  52763. };
  52764. Animatable.prototype._raiseOnAnimationEnd = function () {
  52765. if (this.onAnimationEnd) {
  52766. this.onAnimationEnd();
  52767. }
  52768. this.onAnimationEndObservable.notifyObservers(this);
  52769. };
  52770. Animatable.prototype.stop = function (animationName) {
  52771. if (animationName) {
  52772. var idx = this._scene._activeAnimatables.indexOf(this);
  52773. if (idx > -1) {
  52774. var runtimeAnimations = this._runtimeAnimations;
  52775. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52776. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52777. continue;
  52778. }
  52779. runtimeAnimations[index].dispose();
  52780. runtimeAnimations.splice(index, 1);
  52781. }
  52782. if (runtimeAnimations.length == 0) {
  52783. this._scene._activeAnimatables.splice(idx, 1);
  52784. this._raiseOnAnimationEnd();
  52785. }
  52786. }
  52787. }
  52788. else {
  52789. var index = this._scene._activeAnimatables.indexOf(this);
  52790. if (index > -1) {
  52791. this._scene._activeAnimatables.splice(index, 1);
  52792. var runtimeAnimations = this._runtimeAnimations;
  52793. for (var index = 0; index < runtimeAnimations.length; index++) {
  52794. runtimeAnimations[index].dispose();
  52795. }
  52796. this._raiseOnAnimationEnd();
  52797. }
  52798. }
  52799. };
  52800. /**
  52801. * Wait asynchronously for the animation to end
  52802. * @returns a promise which will be fullfilled when the animation ends
  52803. */
  52804. Animatable.prototype.waitAsync = function () {
  52805. var _this = this;
  52806. return new Promise(function (resolve, reject) {
  52807. _this.onAnimationEndObservable.add(function () {
  52808. resolve(_this);
  52809. }, undefined, undefined, _this, true);
  52810. });
  52811. };
  52812. /** @hidden */
  52813. Animatable.prototype._animate = function (delay) {
  52814. if (this._paused) {
  52815. this.animationStarted = false;
  52816. if (this._pausedDelay === null) {
  52817. this._pausedDelay = delay;
  52818. }
  52819. return true;
  52820. }
  52821. if (this._localDelayOffset === null) {
  52822. this._localDelayOffset = delay;
  52823. this._pausedDelay = null;
  52824. }
  52825. else if (this._pausedDelay !== null) {
  52826. this._localDelayOffset += delay - this._pausedDelay;
  52827. this._pausedDelay = null;
  52828. }
  52829. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52830. return true;
  52831. }
  52832. // Animating
  52833. var running = false;
  52834. var runtimeAnimations = this._runtimeAnimations;
  52835. var index;
  52836. for (index = 0; index < runtimeAnimations.length; index++) {
  52837. var animation = runtimeAnimations[index];
  52838. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52839. running = running || isRunning;
  52840. }
  52841. this.animationStarted = running;
  52842. if (!running) {
  52843. // Remove from active animatables
  52844. index = this._scene._activeAnimatables.indexOf(this);
  52845. this._scene._activeAnimatables.splice(index, 1);
  52846. // Dispose all runtime animations
  52847. for (index = 0; index < runtimeAnimations.length; index++) {
  52848. runtimeAnimations[index].dispose();
  52849. }
  52850. this._raiseOnAnimationEnd();
  52851. this.onAnimationEnd = null;
  52852. this.onAnimationEndObservable.clear();
  52853. }
  52854. return running;
  52855. };
  52856. return Animatable;
  52857. }());
  52858. BABYLON.Animatable = Animatable;
  52859. })(BABYLON || (BABYLON = {}));
  52860. //# sourceMappingURL=babylon.animatable.js.map
  52861. var BABYLON;
  52862. (function (BABYLON) {
  52863. var EasingFunction = /** @class */ (function () {
  52864. function EasingFunction() {
  52865. // Properties
  52866. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52867. }
  52868. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52869. get: function () {
  52870. return EasingFunction._EASINGMODE_EASEIN;
  52871. },
  52872. enumerable: true,
  52873. configurable: true
  52874. });
  52875. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52876. get: function () {
  52877. return EasingFunction._EASINGMODE_EASEOUT;
  52878. },
  52879. enumerable: true,
  52880. configurable: true
  52881. });
  52882. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52883. get: function () {
  52884. return EasingFunction._EASINGMODE_EASEINOUT;
  52885. },
  52886. enumerable: true,
  52887. configurable: true
  52888. });
  52889. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52890. var n = Math.min(Math.max(easingMode, 0), 2);
  52891. this._easingMode = n;
  52892. };
  52893. EasingFunction.prototype.getEasingMode = function () {
  52894. return this._easingMode;
  52895. };
  52896. EasingFunction.prototype.easeInCore = function (gradient) {
  52897. throw new Error('You must implement this method');
  52898. };
  52899. EasingFunction.prototype.ease = function (gradient) {
  52900. switch (this._easingMode) {
  52901. case EasingFunction.EASINGMODE_EASEIN:
  52902. return this.easeInCore(gradient);
  52903. case EasingFunction.EASINGMODE_EASEOUT:
  52904. return (1 - this.easeInCore(1 - gradient));
  52905. }
  52906. if (gradient >= 0.5) {
  52907. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52908. }
  52909. return (this.easeInCore(gradient * 2) * 0.5);
  52910. };
  52911. //Statics
  52912. EasingFunction._EASINGMODE_EASEIN = 0;
  52913. EasingFunction._EASINGMODE_EASEOUT = 1;
  52914. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52915. return EasingFunction;
  52916. }());
  52917. BABYLON.EasingFunction = EasingFunction;
  52918. var CircleEase = /** @class */ (function (_super) {
  52919. __extends(CircleEase, _super);
  52920. function CircleEase() {
  52921. return _super !== null && _super.apply(this, arguments) || this;
  52922. }
  52923. CircleEase.prototype.easeInCore = function (gradient) {
  52924. gradient = Math.max(0, Math.min(1, gradient));
  52925. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52926. };
  52927. return CircleEase;
  52928. }(EasingFunction));
  52929. BABYLON.CircleEase = CircleEase;
  52930. var BackEase = /** @class */ (function (_super) {
  52931. __extends(BackEase, _super);
  52932. function BackEase(amplitude) {
  52933. if (amplitude === void 0) { amplitude = 1; }
  52934. var _this = _super.call(this) || this;
  52935. _this.amplitude = amplitude;
  52936. return _this;
  52937. }
  52938. BackEase.prototype.easeInCore = function (gradient) {
  52939. var num = Math.max(0, this.amplitude);
  52940. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52941. };
  52942. return BackEase;
  52943. }(EasingFunction));
  52944. BABYLON.BackEase = BackEase;
  52945. var BounceEase = /** @class */ (function (_super) {
  52946. __extends(BounceEase, _super);
  52947. function BounceEase(bounces, bounciness) {
  52948. if (bounces === void 0) { bounces = 3; }
  52949. if (bounciness === void 0) { bounciness = 2; }
  52950. var _this = _super.call(this) || this;
  52951. _this.bounces = bounces;
  52952. _this.bounciness = bounciness;
  52953. return _this;
  52954. }
  52955. BounceEase.prototype.easeInCore = function (gradient) {
  52956. var y = Math.max(0.0, this.bounces);
  52957. var bounciness = this.bounciness;
  52958. if (bounciness <= 1.0) {
  52959. bounciness = 1.001;
  52960. }
  52961. var num9 = Math.pow(bounciness, y);
  52962. var num5 = 1.0 - bounciness;
  52963. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52964. var num15 = gradient * num4;
  52965. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52966. var num3 = Math.floor(num65);
  52967. var num13 = num3 + 1.0;
  52968. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52969. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52970. var num7 = (num8 + num12) * 0.5;
  52971. var num6 = gradient - num7;
  52972. var num2 = num7 - num8;
  52973. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52974. };
  52975. return BounceEase;
  52976. }(EasingFunction));
  52977. BABYLON.BounceEase = BounceEase;
  52978. var CubicEase = /** @class */ (function (_super) {
  52979. __extends(CubicEase, _super);
  52980. function CubicEase() {
  52981. return _super !== null && _super.apply(this, arguments) || this;
  52982. }
  52983. CubicEase.prototype.easeInCore = function (gradient) {
  52984. return (gradient * gradient * gradient);
  52985. };
  52986. return CubicEase;
  52987. }(EasingFunction));
  52988. BABYLON.CubicEase = CubicEase;
  52989. var ElasticEase = /** @class */ (function (_super) {
  52990. __extends(ElasticEase, _super);
  52991. function ElasticEase(oscillations, springiness) {
  52992. if (oscillations === void 0) { oscillations = 3; }
  52993. if (springiness === void 0) { springiness = 3; }
  52994. var _this = _super.call(this) || this;
  52995. _this.oscillations = oscillations;
  52996. _this.springiness = springiness;
  52997. return _this;
  52998. }
  52999. ElasticEase.prototype.easeInCore = function (gradient) {
  53000. var num2;
  53001. var num3 = Math.max(0.0, this.oscillations);
  53002. var num = Math.max(0.0, this.springiness);
  53003. if (num == 0) {
  53004. num2 = gradient;
  53005. }
  53006. else {
  53007. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53008. }
  53009. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53010. };
  53011. return ElasticEase;
  53012. }(EasingFunction));
  53013. BABYLON.ElasticEase = ElasticEase;
  53014. var ExponentialEase = /** @class */ (function (_super) {
  53015. __extends(ExponentialEase, _super);
  53016. function ExponentialEase(exponent) {
  53017. if (exponent === void 0) { exponent = 2; }
  53018. var _this = _super.call(this) || this;
  53019. _this.exponent = exponent;
  53020. return _this;
  53021. }
  53022. ExponentialEase.prototype.easeInCore = function (gradient) {
  53023. if (this.exponent <= 0) {
  53024. return gradient;
  53025. }
  53026. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53027. };
  53028. return ExponentialEase;
  53029. }(EasingFunction));
  53030. BABYLON.ExponentialEase = ExponentialEase;
  53031. var PowerEase = /** @class */ (function (_super) {
  53032. __extends(PowerEase, _super);
  53033. function PowerEase(power) {
  53034. if (power === void 0) { power = 2; }
  53035. var _this = _super.call(this) || this;
  53036. _this.power = power;
  53037. return _this;
  53038. }
  53039. PowerEase.prototype.easeInCore = function (gradient) {
  53040. var y = Math.max(0.0, this.power);
  53041. return Math.pow(gradient, y);
  53042. };
  53043. return PowerEase;
  53044. }(EasingFunction));
  53045. BABYLON.PowerEase = PowerEase;
  53046. var QuadraticEase = /** @class */ (function (_super) {
  53047. __extends(QuadraticEase, _super);
  53048. function QuadraticEase() {
  53049. return _super !== null && _super.apply(this, arguments) || this;
  53050. }
  53051. QuadraticEase.prototype.easeInCore = function (gradient) {
  53052. return (gradient * gradient);
  53053. };
  53054. return QuadraticEase;
  53055. }(EasingFunction));
  53056. BABYLON.QuadraticEase = QuadraticEase;
  53057. var QuarticEase = /** @class */ (function (_super) {
  53058. __extends(QuarticEase, _super);
  53059. function QuarticEase() {
  53060. return _super !== null && _super.apply(this, arguments) || this;
  53061. }
  53062. QuarticEase.prototype.easeInCore = function (gradient) {
  53063. return (gradient * gradient * gradient * gradient);
  53064. };
  53065. return QuarticEase;
  53066. }(EasingFunction));
  53067. BABYLON.QuarticEase = QuarticEase;
  53068. var QuinticEase = /** @class */ (function (_super) {
  53069. __extends(QuinticEase, _super);
  53070. function QuinticEase() {
  53071. return _super !== null && _super.apply(this, arguments) || this;
  53072. }
  53073. QuinticEase.prototype.easeInCore = function (gradient) {
  53074. return (gradient * gradient * gradient * gradient * gradient);
  53075. };
  53076. return QuinticEase;
  53077. }(EasingFunction));
  53078. BABYLON.QuinticEase = QuinticEase;
  53079. var SineEase = /** @class */ (function (_super) {
  53080. __extends(SineEase, _super);
  53081. function SineEase() {
  53082. return _super !== null && _super.apply(this, arguments) || this;
  53083. }
  53084. SineEase.prototype.easeInCore = function (gradient) {
  53085. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53086. };
  53087. return SineEase;
  53088. }(EasingFunction));
  53089. BABYLON.SineEase = SineEase;
  53090. var BezierCurveEase = /** @class */ (function (_super) {
  53091. __extends(BezierCurveEase, _super);
  53092. function BezierCurveEase(x1, y1, x2, y2) {
  53093. if (x1 === void 0) { x1 = 0; }
  53094. if (y1 === void 0) { y1 = 0; }
  53095. if (x2 === void 0) { x2 = 1; }
  53096. if (y2 === void 0) { y2 = 1; }
  53097. var _this = _super.call(this) || this;
  53098. _this.x1 = x1;
  53099. _this.y1 = y1;
  53100. _this.x2 = x2;
  53101. _this.y2 = y2;
  53102. return _this;
  53103. }
  53104. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53105. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53106. };
  53107. return BezierCurveEase;
  53108. }(EasingFunction));
  53109. BABYLON.BezierCurveEase = BezierCurveEase;
  53110. })(BABYLON || (BABYLON = {}));
  53111. //# sourceMappingURL=babylon.easing.js.map
  53112. var BABYLON;
  53113. (function (BABYLON) {
  53114. /**
  53115. * A Condition applied to an Action
  53116. */
  53117. var Condition = /** @class */ (function () {
  53118. /**
  53119. * Creates a new Condition
  53120. * @param actionManager the manager of the action the condition is applied to
  53121. */
  53122. function Condition(actionManager) {
  53123. this._actionManager = actionManager;
  53124. }
  53125. /**
  53126. * Check if the current condition is valid
  53127. * @returns a boolean
  53128. */
  53129. Condition.prototype.isValid = function () {
  53130. return true;
  53131. };
  53132. /**
  53133. * Internal only
  53134. * @hidden
  53135. */
  53136. Condition.prototype._getProperty = function (propertyPath) {
  53137. return this._actionManager._getProperty(propertyPath);
  53138. };
  53139. /**
  53140. * Internal only
  53141. * @hidden
  53142. */
  53143. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53144. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53145. };
  53146. /**
  53147. * Serialize placeholder for child classes
  53148. * @returns the serialized object
  53149. */
  53150. Condition.prototype.serialize = function () {
  53151. };
  53152. /**
  53153. * Internal only
  53154. * @hidden
  53155. */
  53156. Condition.prototype._serialize = function (serializedCondition) {
  53157. return {
  53158. type: 2,
  53159. children: [],
  53160. name: serializedCondition.name,
  53161. properties: serializedCondition.properties
  53162. };
  53163. };
  53164. return Condition;
  53165. }());
  53166. BABYLON.Condition = Condition;
  53167. /**
  53168. * Defines specific conditional operators as extensions of Condition
  53169. */
  53170. var ValueCondition = /** @class */ (function (_super) {
  53171. __extends(ValueCondition, _super);
  53172. /**
  53173. * Creates a new ValueCondition
  53174. * @param actionManager manager for the action the condition applies to
  53175. * @param target for the action
  53176. * @param propertyPath path to specify the property of the target the conditional operator uses
  53177. * @param value the value compared by the conditional operator against the current value of the property
  53178. * @param operator the conditional operator, default ValueCondition.IsEqual
  53179. */
  53180. function ValueCondition(actionManager, target,
  53181. /** path to specify the property of the target the conditional operator uses */
  53182. propertyPath,
  53183. /** the value compared by the conditional operator against the current value of the property */
  53184. value,
  53185. /** the conditional operator, default ValueCondition.IsEqual */
  53186. operator) {
  53187. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53188. var _this = _super.call(this, actionManager) || this;
  53189. _this.propertyPath = propertyPath;
  53190. _this.value = value;
  53191. _this.operator = operator;
  53192. _this._target = target;
  53193. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53194. _this._property = _this._getProperty(_this.propertyPath);
  53195. return _this;
  53196. }
  53197. Object.defineProperty(ValueCondition, "IsEqual", {
  53198. /**
  53199. * returns the number for IsEqual
  53200. */
  53201. get: function () {
  53202. return ValueCondition._IsEqual;
  53203. },
  53204. enumerable: true,
  53205. configurable: true
  53206. });
  53207. Object.defineProperty(ValueCondition, "IsDifferent", {
  53208. /**
  53209. * Returns the number for IsDifferent
  53210. */
  53211. get: function () {
  53212. return ValueCondition._IsDifferent;
  53213. },
  53214. enumerable: true,
  53215. configurable: true
  53216. });
  53217. Object.defineProperty(ValueCondition, "IsGreater", {
  53218. /**
  53219. * Returns the number for IsGreater
  53220. */
  53221. get: function () {
  53222. return ValueCondition._IsGreater;
  53223. },
  53224. enumerable: true,
  53225. configurable: true
  53226. });
  53227. Object.defineProperty(ValueCondition, "IsLesser", {
  53228. /**
  53229. * Returns the number for IsLesser
  53230. */
  53231. get: function () {
  53232. return ValueCondition._IsLesser;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. /**
  53238. * Compares the given value with the property value for the specified conditional operator
  53239. * @returns the result of the comparison
  53240. */
  53241. ValueCondition.prototype.isValid = function () {
  53242. switch (this.operator) {
  53243. case ValueCondition.IsGreater:
  53244. return this._effectiveTarget[this._property] > this.value;
  53245. case ValueCondition.IsLesser:
  53246. return this._effectiveTarget[this._property] < this.value;
  53247. case ValueCondition.IsEqual:
  53248. case ValueCondition.IsDifferent:
  53249. var check;
  53250. if (this.value.equals) {
  53251. check = this.value.equals(this._effectiveTarget[this._property]);
  53252. }
  53253. else {
  53254. check = this.value === this._effectiveTarget[this._property];
  53255. }
  53256. return this.operator === ValueCondition.IsEqual ? check : !check;
  53257. }
  53258. return false;
  53259. };
  53260. /**
  53261. * Serialize the ValueCondition into a JSON compatible object
  53262. * @returns serialization object
  53263. */
  53264. ValueCondition.prototype.serialize = function () {
  53265. return this._serialize({
  53266. name: "ValueCondition",
  53267. properties: [
  53268. BABYLON.Action._GetTargetProperty(this._target),
  53269. { name: "propertyPath", value: this.propertyPath },
  53270. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53271. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53272. ]
  53273. });
  53274. };
  53275. /**
  53276. * Gets the name of the conditional operator for the ValueCondition
  53277. * @param operator the conditional operator
  53278. * @returns the name
  53279. */
  53280. ValueCondition.GetOperatorName = function (operator) {
  53281. switch (operator) {
  53282. case ValueCondition._IsEqual: return "IsEqual";
  53283. case ValueCondition._IsDifferent: return "IsDifferent";
  53284. case ValueCondition._IsGreater: return "IsGreater";
  53285. case ValueCondition._IsLesser: return "IsLesser";
  53286. default: return "";
  53287. }
  53288. };
  53289. /**
  53290. * Internal only
  53291. * @hidden
  53292. */
  53293. ValueCondition._IsEqual = 0;
  53294. /**
  53295. * Internal only
  53296. * @hidden
  53297. */
  53298. ValueCondition._IsDifferent = 1;
  53299. /**
  53300. * Internal only
  53301. * @hidden
  53302. */
  53303. ValueCondition._IsGreater = 2;
  53304. /**
  53305. * Internal only
  53306. * @hidden
  53307. */
  53308. ValueCondition._IsLesser = 3;
  53309. return ValueCondition;
  53310. }(Condition));
  53311. BABYLON.ValueCondition = ValueCondition;
  53312. /**
  53313. * Defines a predicate condition as an extension of Condition
  53314. */
  53315. var PredicateCondition = /** @class */ (function (_super) {
  53316. __extends(PredicateCondition, _super);
  53317. /**
  53318. * Creates a new PredicateCondition
  53319. * @param actionManager manager for the action the condition applies to
  53320. * @param predicate defines the predicate function used to validate the condition
  53321. */
  53322. function PredicateCondition(actionManager,
  53323. /** defines the predicate function used to validate the condition */
  53324. predicate) {
  53325. var _this = _super.call(this, actionManager) || this;
  53326. _this.predicate = predicate;
  53327. return _this;
  53328. }
  53329. /**
  53330. * @returns the validity of the predicate condition
  53331. */
  53332. PredicateCondition.prototype.isValid = function () {
  53333. return this.predicate();
  53334. };
  53335. return PredicateCondition;
  53336. }(Condition));
  53337. BABYLON.PredicateCondition = PredicateCondition;
  53338. /**
  53339. * Defines a state condition as an extension of Condition
  53340. */
  53341. var StateCondition = /** @class */ (function (_super) {
  53342. __extends(StateCondition, _super);
  53343. /**
  53344. * Creates a new StateCondition
  53345. * @param actionManager manager for the action the condition applies to
  53346. * @param target of the condition
  53347. * @param value to compare with target state
  53348. */
  53349. function StateCondition(actionManager, target, value) {
  53350. var _this = _super.call(this, actionManager) || this;
  53351. _this.value = value;
  53352. _this._target = target;
  53353. return _this;
  53354. }
  53355. /**
  53356. * @returns the validity of the state
  53357. */
  53358. StateCondition.prototype.isValid = function () {
  53359. return this._target.state === this.value;
  53360. };
  53361. /**
  53362. * Serialize the StateCondition into a JSON compatible object
  53363. * @returns serialization object
  53364. */
  53365. StateCondition.prototype.serialize = function () {
  53366. return this._serialize({
  53367. name: "StateCondition",
  53368. properties: [
  53369. BABYLON.Action._GetTargetProperty(this._target),
  53370. { name: "value", value: this.value }
  53371. ]
  53372. });
  53373. };
  53374. return StateCondition;
  53375. }(Condition));
  53376. BABYLON.StateCondition = StateCondition;
  53377. })(BABYLON || (BABYLON = {}));
  53378. //# sourceMappingURL=babylon.condition.js.map
  53379. var BABYLON;
  53380. (function (BABYLON) {
  53381. /**
  53382. * The action to be carried out following a trigger
  53383. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53384. */
  53385. var Action = /** @class */ (function () {
  53386. /**
  53387. * Creates a new Action
  53388. * @param triggerOptions the trigger, with or without parameters, for the action
  53389. * @param condition an optional determinant of action
  53390. */
  53391. function Action(
  53392. /** the trigger, with or without parameters, for the action */
  53393. triggerOptions, condition) {
  53394. this.triggerOptions = triggerOptions;
  53395. /**
  53396. * An event triggered prior to action being executed.
  53397. */
  53398. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53399. if (triggerOptions.parameter) {
  53400. this.trigger = triggerOptions.trigger;
  53401. this._triggerParameter = triggerOptions.parameter;
  53402. }
  53403. else {
  53404. this.trigger = triggerOptions;
  53405. }
  53406. this._nextActiveAction = this;
  53407. this._condition = condition;
  53408. }
  53409. /**
  53410. * Internal only
  53411. * @hidden
  53412. */
  53413. Action.prototype._prepare = function () {
  53414. };
  53415. /**
  53416. * Gets the trigger parameters
  53417. * @returns the trigger parameters
  53418. */
  53419. Action.prototype.getTriggerParameter = function () {
  53420. return this._triggerParameter;
  53421. };
  53422. /**
  53423. * Internal only - executes current action event
  53424. * @hidden
  53425. */
  53426. Action.prototype._executeCurrent = function (evt) {
  53427. if (this._nextActiveAction._condition) {
  53428. var condition = this._nextActiveAction._condition;
  53429. var currentRenderId = this._actionManager.getScene().getRenderId();
  53430. // We cache the current evaluation for the current frame
  53431. if (condition._evaluationId === currentRenderId) {
  53432. if (!condition._currentResult) {
  53433. return;
  53434. }
  53435. }
  53436. else {
  53437. condition._evaluationId = currentRenderId;
  53438. if (!condition.isValid()) {
  53439. condition._currentResult = false;
  53440. return;
  53441. }
  53442. condition._currentResult = true;
  53443. }
  53444. }
  53445. this.onBeforeExecuteObservable.notifyObservers(this);
  53446. this._nextActiveAction.execute(evt);
  53447. this.skipToNextActiveAction();
  53448. };
  53449. /**
  53450. * Execute placeholder for child classes
  53451. * @param evt optional action event
  53452. */
  53453. Action.prototype.execute = function (evt) {
  53454. };
  53455. /**
  53456. * Skips to next active action
  53457. */
  53458. Action.prototype.skipToNextActiveAction = function () {
  53459. if (this._nextActiveAction._child) {
  53460. if (!this._nextActiveAction._child._actionManager) {
  53461. this._nextActiveAction._child._actionManager = this._actionManager;
  53462. }
  53463. this._nextActiveAction = this._nextActiveAction._child;
  53464. }
  53465. else {
  53466. this._nextActiveAction = this;
  53467. }
  53468. };
  53469. /**
  53470. * Adds action to chain of actions, may be a DoNothingAction
  53471. * @param action defines the next action to execute
  53472. * @returns The action passed in
  53473. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53474. */
  53475. Action.prototype.then = function (action) {
  53476. this._child = action;
  53477. action._actionManager = this._actionManager;
  53478. action._prepare();
  53479. return action;
  53480. };
  53481. /**
  53482. * Internal only
  53483. * @hidden
  53484. */
  53485. Action.prototype._getProperty = function (propertyPath) {
  53486. return this._actionManager._getProperty(propertyPath);
  53487. };
  53488. /**
  53489. * Internal only
  53490. * @hidden
  53491. */
  53492. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53493. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53494. };
  53495. /**
  53496. * Serialize placeholder for child classes
  53497. * @param parent of child
  53498. * @returns the serialized object
  53499. */
  53500. Action.prototype.serialize = function (parent) {
  53501. };
  53502. /**
  53503. * Internal only called by serialize
  53504. * @hidden
  53505. */
  53506. Action.prototype._serialize = function (serializedAction, parent) {
  53507. var serializationObject = {
  53508. type: 1,
  53509. children: [],
  53510. name: serializedAction.name,
  53511. properties: serializedAction.properties || []
  53512. };
  53513. // Serialize child
  53514. if (this._child) {
  53515. this._child.serialize(serializationObject);
  53516. }
  53517. // Check if "this" has a condition
  53518. if (this._condition) {
  53519. var serializedCondition = this._condition.serialize();
  53520. serializedCondition.children.push(serializationObject);
  53521. if (parent) {
  53522. parent.children.push(serializedCondition);
  53523. }
  53524. return serializedCondition;
  53525. }
  53526. if (parent) {
  53527. parent.children.push(serializationObject);
  53528. }
  53529. return serializationObject;
  53530. };
  53531. /**
  53532. * Internal only
  53533. * @hidden
  53534. */
  53535. Action._SerializeValueAsString = function (value) {
  53536. if (typeof value === "number") {
  53537. return value.toString();
  53538. }
  53539. if (typeof value === "boolean") {
  53540. return value ? "true" : "false";
  53541. }
  53542. if (value instanceof BABYLON.Vector2) {
  53543. return value.x + ", " + value.y;
  53544. }
  53545. if (value instanceof BABYLON.Vector3) {
  53546. return value.x + ", " + value.y + ", " + value.z;
  53547. }
  53548. if (value instanceof BABYLON.Color3) {
  53549. return value.r + ", " + value.g + ", " + value.b;
  53550. }
  53551. if (value instanceof BABYLON.Color4) {
  53552. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53553. }
  53554. return value; // string
  53555. };
  53556. /**
  53557. * Internal only
  53558. * @hidden
  53559. */
  53560. Action._GetTargetProperty = function (target) {
  53561. return {
  53562. name: "target",
  53563. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53564. : target instanceof BABYLON.Light ? "LightProperties"
  53565. : target instanceof BABYLON.Camera ? "CameraProperties"
  53566. : "SceneProperties",
  53567. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53568. };
  53569. };
  53570. return Action;
  53571. }());
  53572. BABYLON.Action = Action;
  53573. })(BABYLON || (BABYLON = {}));
  53574. //# sourceMappingURL=babylon.action.js.map
  53575. var BABYLON;
  53576. (function (BABYLON) {
  53577. /**
  53578. * ActionEvent is the event being sent when an action is triggered.
  53579. */
  53580. var ActionEvent = /** @class */ (function () {
  53581. /**
  53582. * Creates a new ActionEvent
  53583. * @param source The mesh or sprite that triggered the action
  53584. * @param pointerX The X mouse cursor position at the time of the event
  53585. * @param pointerY The Y mouse cursor position at the time of the event
  53586. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53587. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53588. * @param additionalData additional data for the event
  53589. */
  53590. function ActionEvent(
  53591. /** The mesh or sprite that triggered the action */
  53592. source,
  53593. /** The X mouse cursor position at the time of the event */
  53594. pointerX,
  53595. /** The Y mouse cursor position at the time of the event */
  53596. pointerY,
  53597. /** The mesh that is currently pointed at (can be null) */
  53598. meshUnderPointer,
  53599. /** the original (browser) event that triggered the ActionEvent */
  53600. sourceEvent,
  53601. /** additional data for the event */
  53602. additionalData) {
  53603. this.source = source;
  53604. this.pointerX = pointerX;
  53605. this.pointerY = pointerY;
  53606. this.meshUnderPointer = meshUnderPointer;
  53607. this.sourceEvent = sourceEvent;
  53608. this.additionalData = additionalData;
  53609. }
  53610. /**
  53611. * Helper function to auto-create an ActionEvent from a source mesh.
  53612. * @param source The source mesh that triggered the event
  53613. * @param evt The original (browser) event
  53614. * @param additionalData additional data for the event
  53615. * @returns the new ActionEvent
  53616. */
  53617. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53618. var scene = source.getScene();
  53619. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53620. };
  53621. /**
  53622. * Helper function to auto-create an ActionEvent from a source sprite
  53623. * @param source The source sprite that triggered the event
  53624. * @param scene Scene associated with the sprite
  53625. * @param evt The original (browser) event
  53626. * @param additionalData additional data for the event
  53627. * @returns the new ActionEvent
  53628. */
  53629. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53630. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53631. };
  53632. /**
  53633. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53634. * @param scene the scene where the event occurred
  53635. * @param evt The original (browser) event
  53636. * @returns the new ActionEvent
  53637. */
  53638. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53639. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53640. };
  53641. /**
  53642. * Helper function to auto-create an ActionEvent from a primitive
  53643. * @param prim defines the target primitive
  53644. * @param pointerPos defines the pointer position
  53645. * @param evt The original (browser) event
  53646. * @param additionalData additional data for the event
  53647. * @returns the new ActionEvent
  53648. */
  53649. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53650. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53651. };
  53652. return ActionEvent;
  53653. }());
  53654. BABYLON.ActionEvent = ActionEvent;
  53655. /**
  53656. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53657. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53658. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53659. */
  53660. var ActionManager = /** @class */ (function () {
  53661. /**
  53662. * Creates a new action manager
  53663. * @param scene defines the hosting scene
  53664. */
  53665. function ActionManager(scene) {
  53666. // Members
  53667. /** Gets the list of actions */
  53668. this.actions = new Array();
  53669. /** Gets the cursor to use when hovering items */
  53670. this.hoverCursor = '';
  53671. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53672. scene._actionManagers.push(this);
  53673. }
  53674. Object.defineProperty(ActionManager, "NothingTrigger", {
  53675. /**
  53676. * Nothing
  53677. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53678. */
  53679. get: function () {
  53680. return ActionManager._NothingTrigger;
  53681. },
  53682. enumerable: true,
  53683. configurable: true
  53684. });
  53685. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53686. /**
  53687. * On pick
  53688. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53689. */
  53690. get: function () {
  53691. return ActionManager._OnPickTrigger;
  53692. },
  53693. enumerable: true,
  53694. configurable: true
  53695. });
  53696. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53697. /**
  53698. * On left pick
  53699. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53700. */
  53701. get: function () {
  53702. return ActionManager._OnLeftPickTrigger;
  53703. },
  53704. enumerable: true,
  53705. configurable: true
  53706. });
  53707. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53708. /**
  53709. * On right pick
  53710. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53711. */
  53712. get: function () {
  53713. return ActionManager._OnRightPickTrigger;
  53714. },
  53715. enumerable: true,
  53716. configurable: true
  53717. });
  53718. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53719. /**
  53720. * On center pick
  53721. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53722. */
  53723. get: function () {
  53724. return ActionManager._OnCenterPickTrigger;
  53725. },
  53726. enumerable: true,
  53727. configurable: true
  53728. });
  53729. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53730. /**
  53731. * On pick down
  53732. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53733. */
  53734. get: function () {
  53735. return ActionManager._OnPickDownTrigger;
  53736. },
  53737. enumerable: true,
  53738. configurable: true
  53739. });
  53740. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53741. /**
  53742. * On double pick
  53743. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53744. */
  53745. get: function () {
  53746. return ActionManager._OnDoublePickTrigger;
  53747. },
  53748. enumerable: true,
  53749. configurable: true
  53750. });
  53751. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53752. /**
  53753. * On pick up
  53754. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53755. */
  53756. get: function () {
  53757. return ActionManager._OnPickUpTrigger;
  53758. },
  53759. enumerable: true,
  53760. configurable: true
  53761. });
  53762. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53763. /**
  53764. * On pick out.
  53765. * This trigger will only be raised if you also declared a OnPickDown
  53766. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53767. */
  53768. get: function () {
  53769. return ActionManager._OnPickOutTrigger;
  53770. },
  53771. enumerable: true,
  53772. configurable: true
  53773. });
  53774. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53775. /**
  53776. * On long press
  53777. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53778. */
  53779. get: function () {
  53780. return ActionManager._OnLongPressTrigger;
  53781. },
  53782. enumerable: true,
  53783. configurable: true
  53784. });
  53785. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53786. /**
  53787. * On pointer over
  53788. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53789. */
  53790. get: function () {
  53791. return ActionManager._OnPointerOverTrigger;
  53792. },
  53793. enumerable: true,
  53794. configurable: true
  53795. });
  53796. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53797. /**
  53798. * On pointer out
  53799. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53800. */
  53801. get: function () {
  53802. return ActionManager._OnPointerOutTrigger;
  53803. },
  53804. enumerable: true,
  53805. configurable: true
  53806. });
  53807. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53808. /**
  53809. * On every frame
  53810. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53811. */
  53812. get: function () {
  53813. return ActionManager._OnEveryFrameTrigger;
  53814. },
  53815. enumerable: true,
  53816. configurable: true
  53817. });
  53818. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53819. /**
  53820. * On intersection enter
  53821. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53822. */
  53823. get: function () {
  53824. return ActionManager._OnIntersectionEnterTrigger;
  53825. },
  53826. enumerable: true,
  53827. configurable: true
  53828. });
  53829. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53830. /**
  53831. * On intersection exit
  53832. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53833. */
  53834. get: function () {
  53835. return ActionManager._OnIntersectionExitTrigger;
  53836. },
  53837. enumerable: true,
  53838. configurable: true
  53839. });
  53840. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53841. /**
  53842. * On key down
  53843. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53844. */
  53845. get: function () {
  53846. return ActionManager._OnKeyDownTrigger;
  53847. },
  53848. enumerable: true,
  53849. configurable: true
  53850. });
  53851. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53852. /**
  53853. * On key up
  53854. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53855. */
  53856. get: function () {
  53857. return ActionManager._OnKeyUpTrigger;
  53858. },
  53859. enumerable: true,
  53860. configurable: true
  53861. });
  53862. // Methods
  53863. /**
  53864. * Releases all associated resources
  53865. */
  53866. ActionManager.prototype.dispose = function () {
  53867. var index = this._scene._actionManagers.indexOf(this);
  53868. for (var i = 0; i < this.actions.length; i++) {
  53869. var action = this.actions[i];
  53870. ActionManager.Triggers[action.trigger]--;
  53871. if (ActionManager.Triggers[action.trigger] === 0) {
  53872. delete ActionManager.Triggers[action.trigger];
  53873. }
  53874. }
  53875. if (index > -1) {
  53876. this._scene._actionManagers.splice(index, 1);
  53877. }
  53878. };
  53879. /**
  53880. * Gets hosting scene
  53881. * @returns the hosting scene
  53882. */
  53883. ActionManager.prototype.getScene = function () {
  53884. return this._scene;
  53885. };
  53886. /**
  53887. * Does this action manager handles actions of any of the given triggers
  53888. * @param triggers defines the triggers to be tested
  53889. * @return a boolean indicating whether one (or more) of the triggers is handled
  53890. */
  53891. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53892. for (var index = 0; index < this.actions.length; index++) {
  53893. var action = this.actions[index];
  53894. if (triggers.indexOf(action.trigger) > -1) {
  53895. return true;
  53896. }
  53897. }
  53898. return false;
  53899. };
  53900. /**
  53901. * Does this action manager handles actions of a given trigger
  53902. * @param trigger defines the trigger to be tested
  53903. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53904. * @return whether the trigger is handled
  53905. */
  53906. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53907. for (var index = 0; index < this.actions.length; index++) {
  53908. var action = this.actions[index];
  53909. if (action.trigger === trigger) {
  53910. if (parameterPredicate) {
  53911. if (parameterPredicate(action.getTriggerParameter())) {
  53912. return true;
  53913. }
  53914. }
  53915. else {
  53916. return true;
  53917. }
  53918. }
  53919. }
  53920. return false;
  53921. };
  53922. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53923. /**
  53924. * Does this action manager has pointer triggers
  53925. */
  53926. get: function () {
  53927. for (var index = 0; index < this.actions.length; index++) {
  53928. var action = this.actions[index];
  53929. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53930. return true;
  53931. }
  53932. }
  53933. return false;
  53934. },
  53935. enumerable: true,
  53936. configurable: true
  53937. });
  53938. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53939. /**
  53940. * Does this action manager has pick triggers
  53941. */
  53942. get: function () {
  53943. for (var index = 0; index < this.actions.length; index++) {
  53944. var action = this.actions[index];
  53945. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53946. return true;
  53947. }
  53948. }
  53949. return false;
  53950. },
  53951. enumerable: true,
  53952. configurable: true
  53953. });
  53954. Object.defineProperty(ActionManager, "HasTriggers", {
  53955. /**
  53956. * Does exist one action manager with at least one trigger
  53957. **/
  53958. get: function () {
  53959. for (var t in ActionManager.Triggers) {
  53960. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53961. return true;
  53962. }
  53963. }
  53964. return false;
  53965. },
  53966. enumerable: true,
  53967. configurable: true
  53968. });
  53969. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53970. /**
  53971. * Does exist one action manager with at least one pick trigger
  53972. **/
  53973. get: function () {
  53974. for (var t in ActionManager.Triggers) {
  53975. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53976. var t_int = parseInt(t);
  53977. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53978. return true;
  53979. }
  53980. }
  53981. }
  53982. return false;
  53983. },
  53984. enumerable: true,
  53985. configurable: true
  53986. });
  53987. /**
  53988. * Does exist one action manager that handles actions of a given trigger
  53989. * @param trigger defines the trigger to be tested
  53990. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53991. **/
  53992. ActionManager.HasSpecificTrigger = function (trigger) {
  53993. for (var t in ActionManager.Triggers) {
  53994. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53995. var t_int = parseInt(t);
  53996. if (t_int === trigger) {
  53997. return true;
  53998. }
  53999. }
  54000. }
  54001. return false;
  54002. };
  54003. /**
  54004. * Registers an action to this action manager
  54005. * @param action defines the action to be registered
  54006. * @return the action amended (prepared) after registration
  54007. */
  54008. ActionManager.prototype.registerAction = function (action) {
  54009. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54010. if (this.getScene().actionManager !== this) {
  54011. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54012. return null;
  54013. }
  54014. }
  54015. this.actions.push(action);
  54016. if (ActionManager.Triggers[action.trigger]) {
  54017. ActionManager.Triggers[action.trigger]++;
  54018. }
  54019. else {
  54020. ActionManager.Triggers[action.trigger] = 1;
  54021. }
  54022. action._actionManager = this;
  54023. action._prepare();
  54024. return action;
  54025. };
  54026. /**
  54027. * Unregisters an action to this action manager
  54028. * @param action defines the action to be unregistered
  54029. * @return a boolean indicating whether the action has been unregistered
  54030. */
  54031. ActionManager.prototype.unregisterAction = function (action) {
  54032. var index = this.actions.indexOf(action);
  54033. if (index !== -1) {
  54034. this.actions.splice(index, 1);
  54035. ActionManager.Triggers[action.trigger] -= 1;
  54036. if (ActionManager.Triggers[action.trigger] === 0) {
  54037. delete ActionManager.Triggers[action.trigger];
  54038. }
  54039. delete action._actionManager;
  54040. return true;
  54041. }
  54042. return false;
  54043. };
  54044. /**
  54045. * Process a specific trigger
  54046. * @param trigger defines the trigger to process
  54047. * @param evt defines the event details to be processed
  54048. */
  54049. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54050. for (var index = 0; index < this.actions.length; index++) {
  54051. var action = this.actions[index];
  54052. if (action.trigger === trigger) {
  54053. if (evt) {
  54054. if (trigger === ActionManager.OnKeyUpTrigger
  54055. || trigger === ActionManager.OnKeyDownTrigger) {
  54056. var parameter = action.getTriggerParameter();
  54057. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54058. if (!parameter.toLowerCase) {
  54059. continue;
  54060. }
  54061. var lowerCase = parameter.toLowerCase();
  54062. if (lowerCase !== evt.sourceEvent.key) {
  54063. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54064. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54065. if (actualkey !== lowerCase) {
  54066. continue;
  54067. }
  54068. }
  54069. }
  54070. }
  54071. }
  54072. action._executeCurrent(evt);
  54073. }
  54074. }
  54075. };
  54076. /** @hidden */
  54077. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54078. var properties = propertyPath.split(".");
  54079. for (var index = 0; index < properties.length - 1; index++) {
  54080. target = target[properties[index]];
  54081. }
  54082. return target;
  54083. };
  54084. /** @hidden */
  54085. ActionManager.prototype._getProperty = function (propertyPath) {
  54086. var properties = propertyPath.split(".");
  54087. return properties[properties.length - 1];
  54088. };
  54089. /**
  54090. * Serialize this manager to a JSON object
  54091. * @param name defines the property name to store this manager
  54092. * @returns a JSON representation of this manager
  54093. */
  54094. ActionManager.prototype.serialize = function (name) {
  54095. var root = {
  54096. children: new Array(),
  54097. name: name,
  54098. type: 3,
  54099. properties: new Array() // Empty for root but required
  54100. };
  54101. for (var i = 0; i < this.actions.length; i++) {
  54102. var triggerObject = {
  54103. type: 0,
  54104. children: new Array(),
  54105. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54106. properties: new Array()
  54107. };
  54108. var triggerOptions = this.actions[i].triggerOptions;
  54109. if (triggerOptions && typeof triggerOptions !== "number") {
  54110. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54111. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54112. }
  54113. else {
  54114. var parameter = {};
  54115. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54116. if (triggerOptions.parameter.mesh) {
  54117. parameter._meshId = triggerOptions.parameter.mesh.id;
  54118. }
  54119. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54120. }
  54121. }
  54122. // Serialize child action, recursively
  54123. this.actions[i].serialize(triggerObject);
  54124. // Add serialized trigger
  54125. root.children.push(triggerObject);
  54126. }
  54127. return root;
  54128. };
  54129. /**
  54130. * Creates a new ActionManager from a JSON data
  54131. * @param parsedActions defines the JSON data to read from
  54132. * @param object defines the hosting mesh
  54133. * @param scene defines the hosting scene
  54134. */
  54135. ActionManager.Parse = function (parsedActions, object, scene) {
  54136. var actionManager = new ActionManager(scene);
  54137. if (object === null)
  54138. scene.actionManager = actionManager;
  54139. else
  54140. object.actionManager = actionManager;
  54141. // instanciate a new object
  54142. var instanciate = function (name, params) {
  54143. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54144. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54145. newInstance.constructor.apply(newInstance, params);
  54146. return newInstance;
  54147. };
  54148. var parseParameter = function (name, value, target, propertyPath) {
  54149. if (propertyPath === null) {
  54150. // String, boolean or float
  54151. var floatValue = parseFloat(value);
  54152. if (value === "true" || value === "false")
  54153. return value === "true";
  54154. else
  54155. return isNaN(floatValue) ? value : floatValue;
  54156. }
  54157. var effectiveTarget = propertyPath.split(".");
  54158. var values = value.split(",");
  54159. // Get effective Target
  54160. for (var i = 0; i < effectiveTarget.length; i++) {
  54161. target = target[effectiveTarget[i]];
  54162. }
  54163. // Return appropriate value with its type
  54164. if (typeof (target) === "boolean")
  54165. return values[0] === "true";
  54166. if (typeof (target) === "string")
  54167. return values[0];
  54168. // Parameters with multiple values such as Vector3 etc.
  54169. var split = new Array();
  54170. for (var i = 0; i < values.length; i++)
  54171. split.push(parseFloat(values[i]));
  54172. if (target instanceof BABYLON.Vector3)
  54173. return BABYLON.Vector3.FromArray(split);
  54174. if (target instanceof BABYLON.Vector4)
  54175. return BABYLON.Vector4.FromArray(split);
  54176. if (target instanceof BABYLON.Color3)
  54177. return BABYLON.Color3.FromArray(split);
  54178. if (target instanceof BABYLON.Color4)
  54179. return BABYLON.Color4.FromArray(split);
  54180. return parseFloat(values[0]);
  54181. };
  54182. // traverse graph per trigger
  54183. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54184. if (combineArray === void 0) { combineArray = null; }
  54185. if (parsedAction.detached)
  54186. return;
  54187. var parameters = new Array();
  54188. var target = null;
  54189. var propertyPath = null;
  54190. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54191. // Parameters
  54192. if (parsedAction.type === 2)
  54193. parameters.push(actionManager);
  54194. else
  54195. parameters.push(trigger);
  54196. if (combine) {
  54197. var actions = new Array();
  54198. for (var j = 0; j < parsedAction.combine.length; j++) {
  54199. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54200. }
  54201. parameters.push(actions);
  54202. }
  54203. else {
  54204. for (var i = 0; i < parsedAction.properties.length; i++) {
  54205. var value = parsedAction.properties[i].value;
  54206. var name = parsedAction.properties[i].name;
  54207. var targetType = parsedAction.properties[i].targetType;
  54208. if (name === "target")
  54209. if (targetType !== null && targetType === "SceneProperties")
  54210. value = target = scene;
  54211. else
  54212. value = target = scene.getNodeByName(value);
  54213. else if (name === "parent")
  54214. value = scene.getNodeByName(value);
  54215. else if (name === "sound")
  54216. value = scene.getSoundByName(value);
  54217. else if (name !== "propertyPath") {
  54218. if (parsedAction.type === 2 && name === "operator")
  54219. value = BABYLON.ValueCondition[value];
  54220. else
  54221. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54222. }
  54223. else {
  54224. propertyPath = value;
  54225. }
  54226. parameters.push(value);
  54227. }
  54228. }
  54229. if (combineArray === null) {
  54230. parameters.push(condition);
  54231. }
  54232. else {
  54233. parameters.push(null);
  54234. }
  54235. // If interpolate value action
  54236. if (parsedAction.name === "InterpolateValueAction") {
  54237. var param = parameters[parameters.length - 2];
  54238. parameters[parameters.length - 1] = param;
  54239. parameters[parameters.length - 2] = condition;
  54240. }
  54241. // Action or condition(s) and not CombineAction
  54242. var newAction = instanciate(parsedAction.name, parameters);
  54243. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54244. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54245. if (action)
  54246. action.then(nothing);
  54247. else
  54248. actionManager.registerAction(nothing);
  54249. action = nothing;
  54250. }
  54251. if (combineArray === null) {
  54252. if (newAction instanceof BABYLON.Condition) {
  54253. condition = newAction;
  54254. newAction = action;
  54255. }
  54256. else {
  54257. condition = null;
  54258. if (action)
  54259. action.then(newAction);
  54260. else
  54261. actionManager.registerAction(newAction);
  54262. }
  54263. }
  54264. else {
  54265. combineArray.push(newAction);
  54266. }
  54267. for (var i = 0; i < parsedAction.children.length; i++)
  54268. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54269. };
  54270. // triggers
  54271. for (var i = 0; i < parsedActions.children.length; i++) {
  54272. var triggerParams;
  54273. var trigger = parsedActions.children[i];
  54274. if (trigger.properties.length > 0) {
  54275. var param = trigger.properties[0].value;
  54276. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54277. if (value._meshId) {
  54278. value.mesh = scene.getMeshByID(value._meshId);
  54279. }
  54280. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54281. }
  54282. else
  54283. triggerParams = ActionManager[trigger.name];
  54284. for (var j = 0; j < trigger.children.length; j++) {
  54285. if (!trigger.detached)
  54286. traverse(trigger.children[j], triggerParams, null, null);
  54287. }
  54288. }
  54289. };
  54290. /**
  54291. * Get a trigger name by index
  54292. * @param trigger defines the trigger index
  54293. * @returns a trigger name
  54294. */
  54295. ActionManager.GetTriggerName = function (trigger) {
  54296. switch (trigger) {
  54297. case 0: return "NothingTrigger";
  54298. case 1: return "OnPickTrigger";
  54299. case 2: return "OnLeftPickTrigger";
  54300. case 3: return "OnRightPickTrigger";
  54301. case 4: return "OnCenterPickTrigger";
  54302. case 5: return "OnPickDownTrigger";
  54303. case 6: return "OnPickUpTrigger";
  54304. case 7: return "OnLongPressTrigger";
  54305. case 8: return "OnPointerOverTrigger";
  54306. case 9: return "OnPointerOutTrigger";
  54307. case 10: return "OnEveryFrameTrigger";
  54308. case 11: return "OnIntersectionEnterTrigger";
  54309. case 12: return "OnIntersectionExitTrigger";
  54310. case 13: return "OnKeyDownTrigger";
  54311. case 14: return "OnKeyUpTrigger";
  54312. case 15: return "OnPickOutTrigger";
  54313. default: return "";
  54314. }
  54315. };
  54316. // Statics
  54317. ActionManager._NothingTrigger = 0;
  54318. ActionManager._OnPickTrigger = 1;
  54319. ActionManager._OnLeftPickTrigger = 2;
  54320. ActionManager._OnRightPickTrigger = 3;
  54321. ActionManager._OnCenterPickTrigger = 4;
  54322. ActionManager._OnPickDownTrigger = 5;
  54323. ActionManager._OnDoublePickTrigger = 6;
  54324. ActionManager._OnPickUpTrigger = 7;
  54325. ActionManager._OnLongPressTrigger = 8;
  54326. ActionManager._OnPointerOverTrigger = 9;
  54327. ActionManager._OnPointerOutTrigger = 10;
  54328. ActionManager._OnEveryFrameTrigger = 11;
  54329. ActionManager._OnIntersectionEnterTrigger = 12;
  54330. ActionManager._OnIntersectionExitTrigger = 13;
  54331. ActionManager._OnKeyDownTrigger = 14;
  54332. ActionManager._OnKeyUpTrigger = 15;
  54333. ActionManager._OnPickOutTrigger = 16;
  54334. /** Gets the list of active triggers */
  54335. ActionManager.Triggers = {};
  54336. return ActionManager;
  54337. }());
  54338. BABYLON.ActionManager = ActionManager;
  54339. })(BABYLON || (BABYLON = {}));
  54340. //# sourceMappingURL=babylon.actionManager.js.map
  54341. var BABYLON;
  54342. (function (BABYLON) {
  54343. var InterpolateValueAction = /** @class */ (function (_super) {
  54344. __extends(InterpolateValueAction, _super);
  54345. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54346. if (duration === void 0) { duration = 1000; }
  54347. var _this = _super.call(this, triggerOptions, condition) || this;
  54348. _this.propertyPath = propertyPath;
  54349. _this.value = value;
  54350. _this.duration = duration;
  54351. _this.stopOtherAnimations = stopOtherAnimations;
  54352. _this.onInterpolationDone = onInterpolationDone;
  54353. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54354. _this._target = _this._effectiveTarget = target;
  54355. return _this;
  54356. }
  54357. InterpolateValueAction.prototype._prepare = function () {
  54358. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54359. this._property = this._getProperty(this.propertyPath);
  54360. };
  54361. InterpolateValueAction.prototype.execute = function () {
  54362. var _this = this;
  54363. var scene = this._actionManager.getScene();
  54364. var keys = [
  54365. {
  54366. frame: 0,
  54367. value: this._effectiveTarget[this._property]
  54368. }, {
  54369. frame: 100,
  54370. value: this.value
  54371. }
  54372. ];
  54373. var dataType;
  54374. if (typeof this.value === "number") {
  54375. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54376. }
  54377. else if (this.value instanceof BABYLON.Color3) {
  54378. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54379. }
  54380. else if (this.value instanceof BABYLON.Vector3) {
  54381. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54382. }
  54383. else if (this.value instanceof BABYLON.Matrix) {
  54384. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54385. }
  54386. else if (this.value instanceof BABYLON.Quaternion) {
  54387. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54388. }
  54389. else {
  54390. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54391. return;
  54392. }
  54393. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54394. animation.setKeys(keys);
  54395. if (this.stopOtherAnimations) {
  54396. scene.stopAnimation(this._effectiveTarget);
  54397. }
  54398. var wrapper = function () {
  54399. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54400. if (_this.onInterpolationDone) {
  54401. _this.onInterpolationDone();
  54402. }
  54403. };
  54404. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54405. };
  54406. InterpolateValueAction.prototype.serialize = function (parent) {
  54407. return _super.prototype._serialize.call(this, {
  54408. name: "InterpolateValueAction",
  54409. properties: [
  54410. BABYLON.Action._GetTargetProperty(this._target),
  54411. { name: "propertyPath", value: this.propertyPath },
  54412. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54413. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54414. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54415. ]
  54416. }, parent);
  54417. };
  54418. return InterpolateValueAction;
  54419. }(BABYLON.Action));
  54420. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54421. })(BABYLON || (BABYLON = {}));
  54422. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54423. var BABYLON;
  54424. (function (BABYLON) {
  54425. var SwitchBooleanAction = /** @class */ (function (_super) {
  54426. __extends(SwitchBooleanAction, _super);
  54427. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54428. var _this = _super.call(this, triggerOptions, condition) || this;
  54429. _this.propertyPath = propertyPath;
  54430. _this._target = _this._effectiveTarget = target;
  54431. return _this;
  54432. }
  54433. SwitchBooleanAction.prototype._prepare = function () {
  54434. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54435. this._property = this._getProperty(this.propertyPath);
  54436. };
  54437. SwitchBooleanAction.prototype.execute = function () {
  54438. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54439. };
  54440. SwitchBooleanAction.prototype.serialize = function (parent) {
  54441. return _super.prototype._serialize.call(this, {
  54442. name: "SwitchBooleanAction",
  54443. properties: [
  54444. BABYLON.Action._GetTargetProperty(this._target),
  54445. { name: "propertyPath", value: this.propertyPath }
  54446. ]
  54447. }, parent);
  54448. };
  54449. return SwitchBooleanAction;
  54450. }(BABYLON.Action));
  54451. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54452. var SetStateAction = /** @class */ (function (_super) {
  54453. __extends(SetStateAction, _super);
  54454. function SetStateAction(triggerOptions, target, value, condition) {
  54455. var _this = _super.call(this, triggerOptions, condition) || this;
  54456. _this.value = value;
  54457. _this._target = target;
  54458. return _this;
  54459. }
  54460. SetStateAction.prototype.execute = function () {
  54461. this._target.state = this.value;
  54462. };
  54463. SetStateAction.prototype.serialize = function (parent) {
  54464. return _super.prototype._serialize.call(this, {
  54465. name: "SetStateAction",
  54466. properties: [
  54467. BABYLON.Action._GetTargetProperty(this._target),
  54468. { name: "value", value: this.value }
  54469. ]
  54470. }, parent);
  54471. };
  54472. return SetStateAction;
  54473. }(BABYLON.Action));
  54474. BABYLON.SetStateAction = SetStateAction;
  54475. var SetValueAction = /** @class */ (function (_super) {
  54476. __extends(SetValueAction, _super);
  54477. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54478. var _this = _super.call(this, triggerOptions, condition) || this;
  54479. _this.propertyPath = propertyPath;
  54480. _this.value = value;
  54481. _this._target = _this._effectiveTarget = target;
  54482. return _this;
  54483. }
  54484. SetValueAction.prototype._prepare = function () {
  54485. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54486. this._property = this._getProperty(this.propertyPath);
  54487. };
  54488. SetValueAction.prototype.execute = function () {
  54489. this._effectiveTarget[this._property] = this.value;
  54490. if (this._target.markAsDirty) {
  54491. this._target.markAsDirty(this._property);
  54492. }
  54493. };
  54494. SetValueAction.prototype.serialize = function (parent) {
  54495. return _super.prototype._serialize.call(this, {
  54496. name: "SetValueAction",
  54497. properties: [
  54498. BABYLON.Action._GetTargetProperty(this._target),
  54499. { name: "propertyPath", value: this.propertyPath },
  54500. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54501. ]
  54502. }, parent);
  54503. };
  54504. return SetValueAction;
  54505. }(BABYLON.Action));
  54506. BABYLON.SetValueAction = SetValueAction;
  54507. var IncrementValueAction = /** @class */ (function (_super) {
  54508. __extends(IncrementValueAction, _super);
  54509. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54510. var _this = _super.call(this, triggerOptions, condition) || this;
  54511. _this.propertyPath = propertyPath;
  54512. _this.value = value;
  54513. _this._target = _this._effectiveTarget = target;
  54514. return _this;
  54515. }
  54516. IncrementValueAction.prototype._prepare = function () {
  54517. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54518. this._property = this._getProperty(this.propertyPath);
  54519. if (typeof this._effectiveTarget[this._property] !== "number") {
  54520. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54521. }
  54522. };
  54523. IncrementValueAction.prototype.execute = function () {
  54524. this._effectiveTarget[this._property] += this.value;
  54525. if (this._target.markAsDirty) {
  54526. this._target.markAsDirty(this._property);
  54527. }
  54528. };
  54529. IncrementValueAction.prototype.serialize = function (parent) {
  54530. return _super.prototype._serialize.call(this, {
  54531. name: "IncrementValueAction",
  54532. properties: [
  54533. BABYLON.Action._GetTargetProperty(this._target),
  54534. { name: "propertyPath", value: this.propertyPath },
  54535. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54536. ]
  54537. }, parent);
  54538. };
  54539. return IncrementValueAction;
  54540. }(BABYLON.Action));
  54541. BABYLON.IncrementValueAction = IncrementValueAction;
  54542. var PlayAnimationAction = /** @class */ (function (_super) {
  54543. __extends(PlayAnimationAction, _super);
  54544. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54545. var _this = _super.call(this, triggerOptions, condition) || this;
  54546. _this.from = from;
  54547. _this.to = to;
  54548. _this.loop = loop;
  54549. _this._target = target;
  54550. return _this;
  54551. }
  54552. PlayAnimationAction.prototype._prepare = function () {
  54553. };
  54554. PlayAnimationAction.prototype.execute = function () {
  54555. var scene = this._actionManager.getScene();
  54556. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54557. };
  54558. PlayAnimationAction.prototype.serialize = function (parent) {
  54559. return _super.prototype._serialize.call(this, {
  54560. name: "PlayAnimationAction",
  54561. properties: [
  54562. BABYLON.Action._GetTargetProperty(this._target),
  54563. { name: "from", value: String(this.from) },
  54564. { name: "to", value: String(this.to) },
  54565. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54566. ]
  54567. }, parent);
  54568. };
  54569. return PlayAnimationAction;
  54570. }(BABYLON.Action));
  54571. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54572. var StopAnimationAction = /** @class */ (function (_super) {
  54573. __extends(StopAnimationAction, _super);
  54574. function StopAnimationAction(triggerOptions, target, condition) {
  54575. var _this = _super.call(this, triggerOptions, condition) || this;
  54576. _this._target = target;
  54577. return _this;
  54578. }
  54579. StopAnimationAction.prototype._prepare = function () {
  54580. };
  54581. StopAnimationAction.prototype.execute = function () {
  54582. var scene = this._actionManager.getScene();
  54583. scene.stopAnimation(this._target);
  54584. };
  54585. StopAnimationAction.prototype.serialize = function (parent) {
  54586. return _super.prototype._serialize.call(this, {
  54587. name: "StopAnimationAction",
  54588. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54589. }, parent);
  54590. };
  54591. return StopAnimationAction;
  54592. }(BABYLON.Action));
  54593. BABYLON.StopAnimationAction = StopAnimationAction;
  54594. var DoNothingAction = /** @class */ (function (_super) {
  54595. __extends(DoNothingAction, _super);
  54596. function DoNothingAction(triggerOptions, condition) {
  54597. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54598. return _super.call(this, triggerOptions, condition) || this;
  54599. }
  54600. DoNothingAction.prototype.execute = function () {
  54601. };
  54602. DoNothingAction.prototype.serialize = function (parent) {
  54603. return _super.prototype._serialize.call(this, {
  54604. name: "DoNothingAction",
  54605. properties: []
  54606. }, parent);
  54607. };
  54608. return DoNothingAction;
  54609. }(BABYLON.Action));
  54610. BABYLON.DoNothingAction = DoNothingAction;
  54611. var CombineAction = /** @class */ (function (_super) {
  54612. __extends(CombineAction, _super);
  54613. function CombineAction(triggerOptions, children, condition) {
  54614. var _this = _super.call(this, triggerOptions, condition) || this;
  54615. _this.children = children;
  54616. return _this;
  54617. }
  54618. CombineAction.prototype._prepare = function () {
  54619. for (var index = 0; index < this.children.length; index++) {
  54620. this.children[index]._actionManager = this._actionManager;
  54621. this.children[index]._prepare();
  54622. }
  54623. };
  54624. CombineAction.prototype.execute = function (evt) {
  54625. for (var index = 0; index < this.children.length; index++) {
  54626. this.children[index].execute(evt);
  54627. }
  54628. };
  54629. CombineAction.prototype.serialize = function (parent) {
  54630. var serializationObject = _super.prototype._serialize.call(this, {
  54631. name: "CombineAction",
  54632. properties: [],
  54633. combine: []
  54634. }, parent);
  54635. for (var i = 0; i < this.children.length; i++) {
  54636. serializationObject.combine.push(this.children[i].serialize(null));
  54637. }
  54638. return serializationObject;
  54639. };
  54640. return CombineAction;
  54641. }(BABYLON.Action));
  54642. BABYLON.CombineAction = CombineAction;
  54643. var ExecuteCodeAction = /** @class */ (function (_super) {
  54644. __extends(ExecuteCodeAction, _super);
  54645. function ExecuteCodeAction(triggerOptions, func, condition) {
  54646. var _this = _super.call(this, triggerOptions, condition) || this;
  54647. _this.func = func;
  54648. return _this;
  54649. }
  54650. ExecuteCodeAction.prototype.execute = function (evt) {
  54651. this.func(evt);
  54652. };
  54653. return ExecuteCodeAction;
  54654. }(BABYLON.Action));
  54655. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54656. var SetParentAction = /** @class */ (function (_super) {
  54657. __extends(SetParentAction, _super);
  54658. function SetParentAction(triggerOptions, target, parent, condition) {
  54659. var _this = _super.call(this, triggerOptions, condition) || this;
  54660. _this._target = target;
  54661. _this._parent = parent;
  54662. return _this;
  54663. }
  54664. SetParentAction.prototype._prepare = function () {
  54665. };
  54666. SetParentAction.prototype.execute = function () {
  54667. if (this._target.parent === this._parent) {
  54668. return;
  54669. }
  54670. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54671. invertParentWorldMatrix.invert();
  54672. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54673. this._target.parent = this._parent;
  54674. };
  54675. SetParentAction.prototype.serialize = function (parent) {
  54676. return _super.prototype._serialize.call(this, {
  54677. name: "SetParentAction",
  54678. properties: [
  54679. BABYLON.Action._GetTargetProperty(this._target),
  54680. BABYLON.Action._GetTargetProperty(this._parent),
  54681. ]
  54682. }, parent);
  54683. };
  54684. return SetParentAction;
  54685. }(BABYLON.Action));
  54686. BABYLON.SetParentAction = SetParentAction;
  54687. var PlaySoundAction = /** @class */ (function (_super) {
  54688. __extends(PlaySoundAction, _super);
  54689. function PlaySoundAction(triggerOptions, sound, condition) {
  54690. var _this = _super.call(this, triggerOptions, condition) || this;
  54691. _this._sound = sound;
  54692. return _this;
  54693. }
  54694. PlaySoundAction.prototype._prepare = function () {
  54695. };
  54696. PlaySoundAction.prototype.execute = function () {
  54697. if (this._sound !== undefined)
  54698. this._sound.play();
  54699. };
  54700. PlaySoundAction.prototype.serialize = function (parent) {
  54701. return _super.prototype._serialize.call(this, {
  54702. name: "PlaySoundAction",
  54703. properties: [{ name: "sound", value: this._sound.name }]
  54704. }, parent);
  54705. };
  54706. return PlaySoundAction;
  54707. }(BABYLON.Action));
  54708. BABYLON.PlaySoundAction = PlaySoundAction;
  54709. var StopSoundAction = /** @class */ (function (_super) {
  54710. __extends(StopSoundAction, _super);
  54711. function StopSoundAction(triggerOptions, sound, condition) {
  54712. var _this = _super.call(this, triggerOptions, condition) || this;
  54713. _this._sound = sound;
  54714. return _this;
  54715. }
  54716. StopSoundAction.prototype._prepare = function () {
  54717. };
  54718. StopSoundAction.prototype.execute = function () {
  54719. if (this._sound !== undefined)
  54720. this._sound.stop();
  54721. };
  54722. StopSoundAction.prototype.serialize = function (parent) {
  54723. return _super.prototype._serialize.call(this, {
  54724. name: "StopSoundAction",
  54725. properties: [{ name: "sound", value: this._sound.name }]
  54726. }, parent);
  54727. };
  54728. return StopSoundAction;
  54729. }(BABYLON.Action));
  54730. BABYLON.StopSoundAction = StopSoundAction;
  54731. })(BABYLON || (BABYLON = {}));
  54732. //# sourceMappingURL=babylon.directActions.js.map
  54733. var BABYLON;
  54734. (function (BABYLON) {
  54735. var SpriteManager = /** @class */ (function () {
  54736. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54737. if (epsilon === void 0) { epsilon = 0.01; }
  54738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54739. this.name = name;
  54740. this.sprites = new Array();
  54741. this.renderingGroupId = 0;
  54742. this.layerMask = 0x0FFFFFFF;
  54743. this.fogEnabled = true;
  54744. this.isPickable = false;
  54745. /**
  54746. * An event triggered when the manager is disposed.
  54747. */
  54748. this.onDisposeObservable = new BABYLON.Observable();
  54749. this._vertexBuffers = {};
  54750. this._capacity = capacity;
  54751. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54752. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54753. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54754. if (cellSize.width && cellSize.height) {
  54755. this.cellWidth = cellSize.width;
  54756. this.cellHeight = cellSize.height;
  54757. }
  54758. else if (cellSize !== undefined) {
  54759. this.cellWidth = cellSize;
  54760. this.cellHeight = cellSize;
  54761. }
  54762. else {
  54763. return;
  54764. }
  54765. this._epsilon = epsilon;
  54766. this._scene = scene;
  54767. this._scene.spriteManagers.push(this);
  54768. var indices = [];
  54769. var index = 0;
  54770. for (var count = 0; count < capacity; count++) {
  54771. indices.push(index);
  54772. indices.push(index + 1);
  54773. indices.push(index + 2);
  54774. indices.push(index);
  54775. indices.push(index + 2);
  54776. indices.push(index + 3);
  54777. index += 4;
  54778. }
  54779. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54780. // VBO
  54781. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54782. this._vertexData = new Float32Array(capacity * 16 * 4);
  54783. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54784. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54785. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54786. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54787. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54788. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54789. this._vertexBuffers["options"] = options;
  54790. this._vertexBuffers["cellInfo"] = cellInfo;
  54791. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54792. // Effects
  54793. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54794. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54795. }
  54796. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54797. set: function (callback) {
  54798. if (this._onDisposeObserver) {
  54799. this.onDisposeObservable.remove(this._onDisposeObserver);
  54800. }
  54801. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54802. },
  54803. enumerable: true,
  54804. configurable: true
  54805. });
  54806. Object.defineProperty(SpriteManager.prototype, "texture", {
  54807. get: function () {
  54808. return this._spriteTexture;
  54809. },
  54810. set: function (value) {
  54811. this._spriteTexture = value;
  54812. },
  54813. enumerable: true,
  54814. configurable: true
  54815. });
  54816. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54817. var arrayOffset = index * 16;
  54818. if (offsetX === 0)
  54819. offsetX = this._epsilon;
  54820. else if (offsetX === 1)
  54821. offsetX = 1 - this._epsilon;
  54822. if (offsetY === 0)
  54823. offsetY = this._epsilon;
  54824. else if (offsetY === 1)
  54825. offsetY = 1 - this._epsilon;
  54826. this._vertexData[arrayOffset] = sprite.position.x;
  54827. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54828. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54829. this._vertexData[arrayOffset + 3] = sprite.angle;
  54830. this._vertexData[arrayOffset + 4] = sprite.width;
  54831. this._vertexData[arrayOffset + 5] = sprite.height;
  54832. this._vertexData[arrayOffset + 6] = offsetX;
  54833. this._vertexData[arrayOffset + 7] = offsetY;
  54834. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54835. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54836. var offset = (sprite.cellIndex / rowSize) >> 0;
  54837. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54838. this._vertexData[arrayOffset + 11] = offset;
  54839. // Color
  54840. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54841. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54842. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54843. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54844. };
  54845. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54846. var count = Math.min(this._capacity, this.sprites.length);
  54847. var min = BABYLON.Vector3.Zero();
  54848. var max = BABYLON.Vector3.Zero();
  54849. var distance = Number.MAX_VALUE;
  54850. var currentSprite = null;
  54851. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54852. var cameraView = camera.getViewMatrix();
  54853. for (var index = 0; index < count; index++) {
  54854. var sprite = this.sprites[index];
  54855. if (!sprite) {
  54856. continue;
  54857. }
  54858. if (predicate) {
  54859. if (!predicate(sprite)) {
  54860. continue;
  54861. }
  54862. }
  54863. else if (!sprite.isPickable) {
  54864. continue;
  54865. }
  54866. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54867. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54868. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54869. if (ray.intersectsBoxMinMax(min, max)) {
  54870. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54871. if (distance > currentDistance) {
  54872. distance = currentDistance;
  54873. currentSprite = sprite;
  54874. if (fastCheck) {
  54875. break;
  54876. }
  54877. }
  54878. }
  54879. }
  54880. if (currentSprite) {
  54881. var result = new BABYLON.PickingInfo();
  54882. result.hit = true;
  54883. result.pickedSprite = currentSprite;
  54884. result.distance = distance;
  54885. return result;
  54886. }
  54887. return null;
  54888. };
  54889. SpriteManager.prototype.render = function () {
  54890. // Check
  54891. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54892. return;
  54893. var engine = this._scene.getEngine();
  54894. var baseSize = this._spriteTexture.getBaseSize();
  54895. // Sprites
  54896. var deltaTime = engine.getDeltaTime();
  54897. var max = Math.min(this._capacity, this.sprites.length);
  54898. var rowSize = baseSize.width / this.cellWidth;
  54899. var offset = 0;
  54900. for (var index = 0; index < max; index++) {
  54901. var sprite = this.sprites[index];
  54902. if (!sprite) {
  54903. continue;
  54904. }
  54905. sprite._animate(deltaTime);
  54906. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54907. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54908. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54909. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54910. }
  54911. this._buffer.update(this._vertexData);
  54912. // Render
  54913. var effect = this._effectBase;
  54914. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54915. effect = this._effectFog;
  54916. }
  54917. engine.enableEffect(effect);
  54918. var viewMatrix = this._scene.getViewMatrix();
  54919. effect.setTexture("diffuseSampler", this._spriteTexture);
  54920. effect.setMatrix("view", viewMatrix);
  54921. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54922. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54923. // Fog
  54924. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54925. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54926. effect.setColor3("vFogColor", this._scene.fogColor);
  54927. }
  54928. // VBOs
  54929. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54930. // Draw order
  54931. engine.setDepthFunctionToLessOrEqual();
  54932. effect.setBool("alphaTest", true);
  54933. engine.setColorWrite(false);
  54934. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54935. engine.setColorWrite(true);
  54936. effect.setBool("alphaTest", false);
  54937. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54938. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54939. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54940. };
  54941. SpriteManager.prototype.dispose = function () {
  54942. if (this._buffer) {
  54943. this._buffer.dispose();
  54944. this._buffer = null;
  54945. }
  54946. if (this._indexBuffer) {
  54947. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54948. this._indexBuffer = null;
  54949. }
  54950. if (this._spriteTexture) {
  54951. this._spriteTexture.dispose();
  54952. this._spriteTexture = null;
  54953. }
  54954. // Remove from scene
  54955. var index = this._scene.spriteManagers.indexOf(this);
  54956. this._scene.spriteManagers.splice(index, 1);
  54957. // Callback
  54958. this.onDisposeObservable.notifyObservers(this);
  54959. this.onDisposeObservable.clear();
  54960. };
  54961. return SpriteManager;
  54962. }());
  54963. BABYLON.SpriteManager = SpriteManager;
  54964. })(BABYLON || (BABYLON = {}));
  54965. //# sourceMappingURL=babylon.spriteManager.js.map
  54966. var BABYLON;
  54967. (function (BABYLON) {
  54968. var Sprite = /** @class */ (function () {
  54969. function Sprite(name, manager) {
  54970. this.name = name;
  54971. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54972. this.width = 1.0;
  54973. this.height = 1.0;
  54974. this.angle = 0;
  54975. this.cellIndex = 0;
  54976. this.invertU = 0;
  54977. this.invertV = 0;
  54978. this.animations = new Array();
  54979. this.isPickable = false;
  54980. this._animationStarted = false;
  54981. this._loopAnimation = false;
  54982. this._fromIndex = 0;
  54983. this._toIndex = 0;
  54984. this._delay = 0;
  54985. this._direction = 1;
  54986. this._time = 0;
  54987. this._manager = manager;
  54988. this._manager.sprites.push(this);
  54989. this.position = BABYLON.Vector3.Zero();
  54990. }
  54991. Object.defineProperty(Sprite.prototype, "size", {
  54992. get: function () {
  54993. return this.width;
  54994. },
  54995. set: function (value) {
  54996. this.width = value;
  54997. this.height = value;
  54998. },
  54999. enumerable: true,
  55000. configurable: true
  55001. });
  55002. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55003. this._fromIndex = from;
  55004. this._toIndex = to;
  55005. this._loopAnimation = loop;
  55006. this._delay = delay;
  55007. this._animationStarted = true;
  55008. this._direction = from < to ? 1 : -1;
  55009. this.cellIndex = from;
  55010. this._time = 0;
  55011. this._onAnimationEnd = onAnimationEnd;
  55012. };
  55013. Sprite.prototype.stopAnimation = function () {
  55014. this._animationStarted = false;
  55015. };
  55016. Sprite.prototype._animate = function (deltaTime) {
  55017. if (!this._animationStarted)
  55018. return;
  55019. this._time += deltaTime;
  55020. if (this._time > this._delay) {
  55021. this._time = this._time % this._delay;
  55022. this.cellIndex += this._direction;
  55023. if (this.cellIndex > this._toIndex) {
  55024. if (this._loopAnimation) {
  55025. this.cellIndex = this._fromIndex;
  55026. }
  55027. else {
  55028. this.cellIndex = this._toIndex;
  55029. this._animationStarted = false;
  55030. if (this._onAnimationEnd) {
  55031. this._onAnimationEnd();
  55032. }
  55033. if (this.disposeWhenFinishedAnimating) {
  55034. this.dispose();
  55035. }
  55036. }
  55037. }
  55038. }
  55039. };
  55040. Sprite.prototype.dispose = function () {
  55041. for (var i = 0; i < this._manager.sprites.length; i++) {
  55042. if (this._manager.sprites[i] == this) {
  55043. this._manager.sprites.splice(i, 1);
  55044. }
  55045. }
  55046. };
  55047. return Sprite;
  55048. }());
  55049. BABYLON.Sprite = Sprite;
  55050. })(BABYLON || (BABYLON = {}));
  55051. //# sourceMappingURL=babylon.sprite.js.map
  55052. var BABYLON;
  55053. (function (BABYLON) {
  55054. var IntersectionInfo = /** @class */ (function () {
  55055. function IntersectionInfo(bu, bv, distance) {
  55056. this.bu = bu;
  55057. this.bv = bv;
  55058. this.distance = distance;
  55059. this.faceId = 0;
  55060. this.subMeshId = 0;
  55061. }
  55062. return IntersectionInfo;
  55063. }());
  55064. BABYLON.IntersectionInfo = IntersectionInfo;
  55065. /**
  55066. * Information about the result of picking within a scene
  55067. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55068. */
  55069. var PickingInfo = /** @class */ (function () {
  55070. function PickingInfo() {
  55071. /**
  55072. * If the pick collided with an object
  55073. */
  55074. this.hit = false;
  55075. /**
  55076. * Distance away where the pick collided
  55077. */
  55078. this.distance = 0;
  55079. /**
  55080. * The location of pick collision
  55081. */
  55082. this.pickedPoint = null;
  55083. /**
  55084. * The mesh corrisponding the the pick collision
  55085. */
  55086. this.pickedMesh = null;
  55087. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55088. this.bu = 0;
  55089. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55090. this.bv = 0;
  55091. /** The id of the face on the mesh that was picked */
  55092. this.faceId = -1;
  55093. /** Id of the the submesh that was picked */
  55094. this.subMeshId = 0;
  55095. /** If a sprite was picked, this will be the sprite the pick collided with */
  55096. this.pickedSprite = null;
  55097. /**
  55098. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55099. */
  55100. this.originMesh = null;
  55101. /**
  55102. * The ray that was used to perform the picking.
  55103. */
  55104. this.ray = null;
  55105. }
  55106. /**
  55107. * Gets the normal corrispodning to the face the pick collided with
  55108. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55109. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55110. * @returns The normal corrispodning to the face the pick collided with
  55111. */
  55112. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55113. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55114. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55115. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55116. return null;
  55117. }
  55118. var indices = this.pickedMesh.getIndices();
  55119. if (!indices) {
  55120. return null;
  55121. }
  55122. var result;
  55123. if (useVerticesNormals) {
  55124. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55125. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55126. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55127. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55128. normal0 = normal0.scale(this.bu);
  55129. normal1 = normal1.scale(this.bv);
  55130. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55131. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55132. }
  55133. else {
  55134. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55135. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55136. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55137. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55138. var p1p2 = vertex1.subtract(vertex2);
  55139. var p3p2 = vertex3.subtract(vertex2);
  55140. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55141. }
  55142. if (useWorldCoordinates) {
  55143. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55144. }
  55145. return BABYLON.Vector3.Normalize(result);
  55146. };
  55147. /**
  55148. * Gets the texture coordinates of where the pick occured
  55149. * @returns the vector containing the coordnates of the texture
  55150. */
  55151. PickingInfo.prototype.getTextureCoordinates = function () {
  55152. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55153. return null;
  55154. }
  55155. var indices = this.pickedMesh.getIndices();
  55156. if (!indices) {
  55157. return null;
  55158. }
  55159. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55160. if (!uvs) {
  55161. return null;
  55162. }
  55163. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55164. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55165. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55166. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55167. uv1 = uv1.scale(this.bu);
  55168. uv2 = uv2.scale(this.bv);
  55169. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55170. };
  55171. return PickingInfo;
  55172. }());
  55173. BABYLON.PickingInfo = PickingInfo;
  55174. })(BABYLON || (BABYLON = {}));
  55175. //# sourceMappingURL=babylon.pickingInfo.js.map
  55176. var BABYLON;
  55177. (function (BABYLON) {
  55178. var Ray = /** @class */ (function () {
  55179. function Ray(origin, direction, length) {
  55180. if (length === void 0) { length = Number.MAX_VALUE; }
  55181. this.origin = origin;
  55182. this.direction = direction;
  55183. this.length = length;
  55184. }
  55185. // Methods
  55186. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55187. var d = 0.0;
  55188. var maxValue = Number.MAX_VALUE;
  55189. var inv;
  55190. var min;
  55191. var max;
  55192. var temp;
  55193. if (Math.abs(this.direction.x) < 0.0000001) {
  55194. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55195. return false;
  55196. }
  55197. }
  55198. else {
  55199. inv = 1.0 / this.direction.x;
  55200. min = (minimum.x - this.origin.x) * inv;
  55201. max = (maximum.x - this.origin.x) * inv;
  55202. if (max === -Infinity) {
  55203. max = Infinity;
  55204. }
  55205. if (min > max) {
  55206. temp = min;
  55207. min = max;
  55208. max = temp;
  55209. }
  55210. d = Math.max(min, d);
  55211. maxValue = Math.min(max, maxValue);
  55212. if (d > maxValue) {
  55213. return false;
  55214. }
  55215. }
  55216. if (Math.abs(this.direction.y) < 0.0000001) {
  55217. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55218. return false;
  55219. }
  55220. }
  55221. else {
  55222. inv = 1.0 / this.direction.y;
  55223. min = (minimum.y - this.origin.y) * inv;
  55224. max = (maximum.y - this.origin.y) * inv;
  55225. if (max === -Infinity) {
  55226. max = Infinity;
  55227. }
  55228. if (min > max) {
  55229. temp = min;
  55230. min = max;
  55231. max = temp;
  55232. }
  55233. d = Math.max(min, d);
  55234. maxValue = Math.min(max, maxValue);
  55235. if (d > maxValue) {
  55236. return false;
  55237. }
  55238. }
  55239. if (Math.abs(this.direction.z) < 0.0000001) {
  55240. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55241. return false;
  55242. }
  55243. }
  55244. else {
  55245. inv = 1.0 / this.direction.z;
  55246. min = (minimum.z - this.origin.z) * inv;
  55247. max = (maximum.z - this.origin.z) * inv;
  55248. if (max === -Infinity) {
  55249. max = Infinity;
  55250. }
  55251. if (min > max) {
  55252. temp = min;
  55253. min = max;
  55254. max = temp;
  55255. }
  55256. d = Math.max(min, d);
  55257. maxValue = Math.min(max, maxValue);
  55258. if (d > maxValue) {
  55259. return false;
  55260. }
  55261. }
  55262. return true;
  55263. };
  55264. Ray.prototype.intersectsBox = function (box) {
  55265. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55266. };
  55267. Ray.prototype.intersectsSphere = function (sphere) {
  55268. var x = sphere.center.x - this.origin.x;
  55269. var y = sphere.center.y - this.origin.y;
  55270. var z = sphere.center.z - this.origin.z;
  55271. var pyth = (x * x) + (y * y) + (z * z);
  55272. var rr = sphere.radius * sphere.radius;
  55273. if (pyth <= rr) {
  55274. return true;
  55275. }
  55276. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55277. if (dot < 0.0) {
  55278. return false;
  55279. }
  55280. var temp = pyth - (dot * dot);
  55281. return temp <= rr;
  55282. };
  55283. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55284. if (!this._edge1) {
  55285. this._edge1 = BABYLON.Vector3.Zero();
  55286. this._edge2 = BABYLON.Vector3.Zero();
  55287. this._pvec = BABYLON.Vector3.Zero();
  55288. this._tvec = BABYLON.Vector3.Zero();
  55289. this._qvec = BABYLON.Vector3.Zero();
  55290. }
  55291. vertex1.subtractToRef(vertex0, this._edge1);
  55292. vertex2.subtractToRef(vertex0, this._edge2);
  55293. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55294. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55295. if (det === 0) {
  55296. return null;
  55297. }
  55298. var invdet = 1 / det;
  55299. this.origin.subtractToRef(vertex0, this._tvec);
  55300. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55301. if (bu < 0 || bu > 1.0) {
  55302. return null;
  55303. }
  55304. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55305. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55306. if (bv < 0 || bu + bv > 1.0) {
  55307. return null;
  55308. }
  55309. //check if the distance is longer than the predefined length.
  55310. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55311. if (distance > this.length) {
  55312. return null;
  55313. }
  55314. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55315. };
  55316. Ray.prototype.intersectsPlane = function (plane) {
  55317. var distance;
  55318. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55319. if (Math.abs(result1) < 9.99999997475243E-07) {
  55320. return null;
  55321. }
  55322. else {
  55323. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55324. distance = (-plane.d - result2) / result1;
  55325. if (distance < 0.0) {
  55326. if (distance < -9.99999997475243E-07) {
  55327. return null;
  55328. }
  55329. else {
  55330. return 0;
  55331. }
  55332. }
  55333. return distance;
  55334. }
  55335. };
  55336. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55337. var tm = BABYLON.Tmp.Matrix[0];
  55338. mesh.getWorldMatrix().invertToRef(tm);
  55339. if (this._tmpRay) {
  55340. Ray.TransformToRef(this, tm, this._tmpRay);
  55341. }
  55342. else {
  55343. this._tmpRay = Ray.Transform(this, tm);
  55344. }
  55345. return mesh.intersects(this._tmpRay, fastCheck);
  55346. };
  55347. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55348. if (results) {
  55349. results.length = 0;
  55350. }
  55351. else {
  55352. results = [];
  55353. }
  55354. for (var i = 0; i < meshes.length; i++) {
  55355. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55356. if (pickInfo.hit) {
  55357. results.push(pickInfo);
  55358. }
  55359. }
  55360. results.sort(this._comparePickingInfo);
  55361. return results;
  55362. };
  55363. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55364. if (pickingInfoA.distance < pickingInfoB.distance) {
  55365. return -1;
  55366. }
  55367. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55368. return 1;
  55369. }
  55370. else {
  55371. return 0;
  55372. }
  55373. };
  55374. /**
  55375. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55376. * @param sega the first point of the segment to test the intersection against
  55377. * @param segb the second point of the segment to test the intersection against
  55378. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55379. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55380. */
  55381. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55382. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55383. var u = segb.subtract(sega);
  55384. var v = rsegb.subtract(this.origin);
  55385. var w = sega.subtract(this.origin);
  55386. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55387. var b = BABYLON.Vector3.Dot(u, v);
  55388. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55389. var d = BABYLON.Vector3.Dot(u, w);
  55390. var e = BABYLON.Vector3.Dot(v, w);
  55391. var D = a * c - b * b; // always >= 0
  55392. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55393. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55394. // compute the line parameters of the two closest points
  55395. if (D < Ray.smallnum) { // the lines are almost parallel
  55396. sN = 0.0; // force using point P0 on segment S1
  55397. sD = 1.0; // to prevent possible division by 0.0 later
  55398. tN = e;
  55399. tD = c;
  55400. }
  55401. else { // get the closest points on the infinite lines
  55402. sN = (b * e - c * d);
  55403. tN = (a * e - b * d);
  55404. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55405. sN = 0.0;
  55406. tN = e;
  55407. tD = c;
  55408. }
  55409. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55410. sN = sD;
  55411. tN = e + b;
  55412. tD = c;
  55413. }
  55414. }
  55415. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55416. tN = 0.0;
  55417. // recompute sc for this edge
  55418. if (-d < 0.0) {
  55419. sN = 0.0;
  55420. }
  55421. else if (-d > a)
  55422. sN = sD;
  55423. else {
  55424. sN = -d;
  55425. sD = a;
  55426. }
  55427. }
  55428. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55429. tN = tD;
  55430. // recompute sc for this edge
  55431. if ((-d + b) < 0.0) {
  55432. sN = 0;
  55433. }
  55434. else if ((-d + b) > a) {
  55435. sN = sD;
  55436. }
  55437. else {
  55438. sN = (-d + b);
  55439. sD = a;
  55440. }
  55441. }
  55442. // finally do the division to get sc and tc
  55443. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55444. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55445. // get the difference of the two closest points
  55446. var qtc = v.multiplyByFloats(tc, tc, tc);
  55447. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55448. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55449. if (isIntersected) {
  55450. return qtc.length();
  55451. }
  55452. return -1;
  55453. };
  55454. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55455. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55456. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55457. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55458. this.direction.normalize();
  55459. return this;
  55460. };
  55461. // Statics
  55462. Ray.Zero = function () {
  55463. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55464. };
  55465. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55466. var result = Ray.Zero();
  55467. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55468. };
  55469. /**
  55470. * 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
  55471. * transformed to the given world matrix.
  55472. * @param origin The origin point
  55473. * @param end The end point
  55474. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55475. */
  55476. Ray.CreateNewFromTo = function (origin, end, world) {
  55477. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55478. var direction = end.subtract(origin);
  55479. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55480. direction.normalize();
  55481. return Ray.Transform(new Ray(origin, direction, length), world);
  55482. };
  55483. Ray.Transform = function (ray, matrix) {
  55484. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55485. Ray.TransformToRef(ray, matrix, result);
  55486. return result;
  55487. };
  55488. Ray.TransformToRef = function (ray, matrix, result) {
  55489. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55490. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55491. result.length = ray.length;
  55492. var dir = result.direction;
  55493. var len = dir.length();
  55494. if (!(len === 0 || len === 1)) {
  55495. var num = 1.0 / len;
  55496. dir.x *= num;
  55497. dir.y *= num;
  55498. dir.z *= num;
  55499. result.length *= len;
  55500. }
  55501. };
  55502. Ray.smallnum = 0.00000001;
  55503. Ray.rayl = 10e8;
  55504. return Ray;
  55505. }());
  55506. BABYLON.Ray = Ray;
  55507. })(BABYLON || (BABYLON = {}));
  55508. //# sourceMappingURL=babylon.ray.js.map
  55509. var BABYLON;
  55510. (function (BABYLON) {
  55511. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55512. if (boxMin.x > sphereCenter.x + sphereRadius)
  55513. return false;
  55514. if (sphereCenter.x - sphereRadius > boxMax.x)
  55515. return false;
  55516. if (boxMin.y > sphereCenter.y + sphereRadius)
  55517. return false;
  55518. if (sphereCenter.y - sphereRadius > boxMax.y)
  55519. return false;
  55520. if (boxMin.z > sphereCenter.z + sphereRadius)
  55521. return false;
  55522. if (sphereCenter.z - sphereRadius > boxMax.z)
  55523. return false;
  55524. return true;
  55525. };
  55526. var getLowestRoot = (function () {
  55527. var result = { root: 0, found: false };
  55528. return function (a, b, c, maxR) {
  55529. result.root = 0;
  55530. result.found = false;
  55531. var determinant = b * b - 4.0 * a * c;
  55532. if (determinant < 0)
  55533. return result;
  55534. var sqrtD = Math.sqrt(determinant);
  55535. var r1 = (-b - sqrtD) / (2.0 * a);
  55536. var r2 = (-b + sqrtD) / (2.0 * a);
  55537. if (r1 > r2) {
  55538. var temp = r2;
  55539. r2 = r1;
  55540. r1 = temp;
  55541. }
  55542. if (r1 > 0 && r1 < maxR) {
  55543. result.root = r1;
  55544. result.found = true;
  55545. return result;
  55546. }
  55547. if (r2 > 0 && r2 < maxR) {
  55548. result.root = r2;
  55549. result.found = true;
  55550. return result;
  55551. }
  55552. return result;
  55553. };
  55554. })();
  55555. var Collider = /** @class */ (function () {
  55556. function Collider() {
  55557. this._collisionPoint = BABYLON.Vector3.Zero();
  55558. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55559. this._tempVector = BABYLON.Vector3.Zero();
  55560. this._tempVector2 = BABYLON.Vector3.Zero();
  55561. this._tempVector3 = BABYLON.Vector3.Zero();
  55562. this._tempVector4 = BABYLON.Vector3.Zero();
  55563. this._edge = BABYLON.Vector3.Zero();
  55564. this._baseToVertex = BABYLON.Vector3.Zero();
  55565. this._destinationPoint = BABYLON.Vector3.Zero();
  55566. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55567. this._displacementVector = BABYLON.Vector3.Zero();
  55568. this._radius = BABYLON.Vector3.One();
  55569. this._retry = 0;
  55570. this._basePointWorld = BABYLON.Vector3.Zero();
  55571. this._velocityWorld = BABYLON.Vector3.Zero();
  55572. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55573. this._collisionMask = -1;
  55574. }
  55575. Object.defineProperty(Collider.prototype, "collisionMask", {
  55576. get: function () {
  55577. return this._collisionMask;
  55578. },
  55579. set: function (mask) {
  55580. this._collisionMask = !isNaN(mask) ? mask : -1;
  55581. },
  55582. enumerable: true,
  55583. configurable: true
  55584. });
  55585. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55586. /**
  55587. * Gets the plane normal used to compute the sliding response (in local space)
  55588. */
  55589. get: function () {
  55590. return this._slidePlaneNormal;
  55591. },
  55592. enumerable: true,
  55593. configurable: true
  55594. });
  55595. // Methods
  55596. Collider.prototype._initialize = function (source, dir, e) {
  55597. this._velocity = dir;
  55598. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55599. this._basePoint = source;
  55600. source.multiplyToRef(this._radius, this._basePointWorld);
  55601. dir.multiplyToRef(this._radius, this._velocityWorld);
  55602. this._velocityWorldLength = this._velocityWorld.length();
  55603. this._epsilon = e;
  55604. this.collisionFound = false;
  55605. };
  55606. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55607. pa.subtractToRef(point, this._tempVector);
  55608. pb.subtractToRef(point, this._tempVector2);
  55609. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55610. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55611. if (d < 0)
  55612. return false;
  55613. pc.subtractToRef(point, this._tempVector3);
  55614. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55615. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55616. if (d < 0)
  55617. return false;
  55618. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55619. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55620. return d >= 0;
  55621. };
  55622. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55623. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55624. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55625. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55626. return false;
  55627. }
  55628. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55629. return false;
  55630. return true;
  55631. };
  55632. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55633. var t0;
  55634. var embeddedInPlane = false;
  55635. //defensive programming, actually not needed.
  55636. if (!trianglePlaneArray) {
  55637. trianglePlaneArray = [];
  55638. }
  55639. if (!trianglePlaneArray[faceIndex]) {
  55640. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55641. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55642. }
  55643. var trianglePlane = trianglePlaneArray[faceIndex];
  55644. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55645. return;
  55646. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55647. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55648. if (normalDotVelocity == 0) {
  55649. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55650. return;
  55651. embeddedInPlane = true;
  55652. t0 = 0;
  55653. }
  55654. else {
  55655. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55656. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55657. if (t0 > t1) {
  55658. var temp = t1;
  55659. t1 = t0;
  55660. t0 = temp;
  55661. }
  55662. if (t0 > 1.0 || t1 < 0.0)
  55663. return;
  55664. if (t0 < 0)
  55665. t0 = 0;
  55666. if (t0 > 1.0)
  55667. t0 = 1.0;
  55668. }
  55669. this._collisionPoint.copyFromFloats(0, 0, 0);
  55670. var found = false;
  55671. var t = 1.0;
  55672. if (!embeddedInPlane) {
  55673. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55674. this._velocity.scaleToRef(t0, this._tempVector);
  55675. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55676. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55677. found = true;
  55678. t = t0;
  55679. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55680. }
  55681. }
  55682. if (!found) {
  55683. var velocitySquaredLength = this._velocity.lengthSquared();
  55684. var a = velocitySquaredLength;
  55685. this._basePoint.subtractToRef(p1, this._tempVector);
  55686. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55687. var c = this._tempVector.lengthSquared() - 1.0;
  55688. var lowestRoot = getLowestRoot(a, b, c, t);
  55689. if (lowestRoot.found) {
  55690. t = lowestRoot.root;
  55691. found = true;
  55692. this._collisionPoint.copyFrom(p1);
  55693. }
  55694. this._basePoint.subtractToRef(p2, this._tempVector);
  55695. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55696. c = this._tempVector.lengthSquared() - 1.0;
  55697. lowestRoot = getLowestRoot(a, b, c, t);
  55698. if (lowestRoot.found) {
  55699. t = lowestRoot.root;
  55700. found = true;
  55701. this._collisionPoint.copyFrom(p2);
  55702. }
  55703. this._basePoint.subtractToRef(p3, this._tempVector);
  55704. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55705. c = this._tempVector.lengthSquared() - 1.0;
  55706. lowestRoot = getLowestRoot(a, b, c, t);
  55707. if (lowestRoot.found) {
  55708. t = lowestRoot.root;
  55709. found = true;
  55710. this._collisionPoint.copyFrom(p3);
  55711. }
  55712. p2.subtractToRef(p1, this._edge);
  55713. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55714. var edgeSquaredLength = this._edge.lengthSquared();
  55715. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55716. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55717. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55718. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55719. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55720. lowestRoot = getLowestRoot(a, b, c, t);
  55721. if (lowestRoot.found) {
  55722. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55723. if (f >= 0.0 && f <= 1.0) {
  55724. t = lowestRoot.root;
  55725. found = true;
  55726. this._edge.scaleInPlace(f);
  55727. p1.addToRef(this._edge, this._collisionPoint);
  55728. }
  55729. }
  55730. p3.subtractToRef(p2, this._edge);
  55731. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55732. edgeSquaredLength = this._edge.lengthSquared();
  55733. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55734. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55735. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55736. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55737. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55738. lowestRoot = getLowestRoot(a, b, c, t);
  55739. if (lowestRoot.found) {
  55740. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55741. if (f >= 0.0 && f <= 1.0) {
  55742. t = lowestRoot.root;
  55743. found = true;
  55744. this._edge.scaleInPlace(f);
  55745. p2.addToRef(this._edge, this._collisionPoint);
  55746. }
  55747. }
  55748. p1.subtractToRef(p3, this._edge);
  55749. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55750. edgeSquaredLength = this._edge.lengthSquared();
  55751. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55752. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55753. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55754. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55755. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55756. lowestRoot = getLowestRoot(a, b, c, t);
  55757. if (lowestRoot.found) {
  55758. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55759. if (f >= 0.0 && f <= 1.0) {
  55760. t = lowestRoot.root;
  55761. found = true;
  55762. this._edge.scaleInPlace(f);
  55763. p3.addToRef(this._edge, this._collisionPoint);
  55764. }
  55765. }
  55766. }
  55767. if (found) {
  55768. var distToCollision = t * this._velocity.length();
  55769. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55770. if (!this.intersectionPoint) {
  55771. this.intersectionPoint = this._collisionPoint.clone();
  55772. }
  55773. else {
  55774. this.intersectionPoint.copyFrom(this._collisionPoint);
  55775. }
  55776. this._nearestDistance = distToCollision;
  55777. this.collisionFound = true;
  55778. }
  55779. }
  55780. };
  55781. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55782. for (var i = indexStart; i < indexEnd; i += 3) {
  55783. var p1 = pts[indices[i] - decal];
  55784. var p2 = pts[indices[i + 1] - decal];
  55785. var p3 = pts[indices[i + 2] - decal];
  55786. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55787. }
  55788. };
  55789. Collider.prototype._getResponse = function (pos, vel) {
  55790. pos.addToRef(vel, this._destinationPoint);
  55791. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55792. this._basePoint.addToRef(vel, pos);
  55793. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55794. this._slidePlaneNormal.normalize();
  55795. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55796. pos.addInPlace(this._displacementVector);
  55797. this.intersectionPoint.addInPlace(this._displacementVector);
  55798. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55799. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55800. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55801. };
  55802. return Collider;
  55803. }());
  55804. BABYLON.Collider = Collider;
  55805. })(BABYLON || (BABYLON = {}));
  55806. //# sourceMappingURL=babylon.collider.js.map
  55807. var BABYLON;
  55808. (function (BABYLON) {
  55809. //WebWorker code will be inserted to this variable.
  55810. BABYLON.CollisionWorker = "";
  55811. /** Defines supported task for worker process */
  55812. var WorkerTaskType;
  55813. (function (WorkerTaskType) {
  55814. /** Initialization */
  55815. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55816. /** Update of geometry */
  55817. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55818. /** Evaluate collision */
  55819. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55820. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55821. /** Defines kind of replies returned by worker */
  55822. var WorkerReplyType;
  55823. (function (WorkerReplyType) {
  55824. /** Success */
  55825. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55826. /** Unkown error */
  55827. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55828. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55829. var CollisionCoordinatorWorker = /** @class */ (function () {
  55830. function CollisionCoordinatorWorker() {
  55831. var _this = this;
  55832. this._scaledPosition = BABYLON.Vector3.Zero();
  55833. this._scaledVelocity = BABYLON.Vector3.Zero();
  55834. this.onMeshUpdated = function (transformNode) {
  55835. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55836. };
  55837. this.onGeometryUpdated = function (geometry) {
  55838. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55839. };
  55840. this._afterRender = function () {
  55841. if (!_this._init)
  55842. return;
  55843. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55844. return;
  55845. }
  55846. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55847. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55848. if (_this._runningUpdated > 4) {
  55849. return;
  55850. }
  55851. ++_this._runningUpdated;
  55852. var payload = {
  55853. updatedMeshes: _this._addUpdateMeshesList,
  55854. updatedGeometries: _this._addUpdateGeometriesList,
  55855. removedGeometries: _this._toRemoveGeometryArray,
  55856. removedMeshes: _this._toRemoveMeshesArray
  55857. };
  55858. var message = {
  55859. payload: payload,
  55860. taskType: WorkerTaskType.UPDATE
  55861. };
  55862. var serializable = [];
  55863. for (var id in payload.updatedGeometries) {
  55864. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55865. //prepare transferables
  55866. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55867. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55868. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55869. }
  55870. }
  55871. _this._worker.postMessage(message, serializable);
  55872. _this._addUpdateMeshesList = {};
  55873. _this._addUpdateGeometriesList = {};
  55874. _this._toRemoveGeometryArray = [];
  55875. _this._toRemoveMeshesArray = [];
  55876. };
  55877. this._onMessageFromWorker = function (e) {
  55878. var returnData = e.data;
  55879. if (returnData.error != WorkerReplyType.SUCCESS) {
  55880. //TODO what errors can be returned from the worker?
  55881. BABYLON.Tools.Warn("error returned from worker!");
  55882. return;
  55883. }
  55884. switch (returnData.taskType) {
  55885. case WorkerTaskType.INIT:
  55886. _this._init = true;
  55887. //Update the worked with ALL of the scene's current state
  55888. _this._scene.meshes.forEach(function (mesh) {
  55889. _this.onMeshAdded(mesh);
  55890. });
  55891. _this._scene.getGeometries().forEach(function (geometry) {
  55892. _this.onGeometryAdded(geometry);
  55893. });
  55894. break;
  55895. case WorkerTaskType.UPDATE:
  55896. _this._runningUpdated--;
  55897. break;
  55898. case WorkerTaskType.COLLIDE:
  55899. var returnPayload = returnData.payload;
  55900. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55901. return;
  55902. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55903. if (callback) {
  55904. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55905. if (mesh) {
  55906. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55907. }
  55908. }
  55909. //cleanup
  55910. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55911. break;
  55912. }
  55913. };
  55914. this._collisionsCallbackArray = [];
  55915. this._init = false;
  55916. this._runningUpdated = 0;
  55917. this._addUpdateMeshesList = {};
  55918. this._addUpdateGeometriesList = {};
  55919. this._toRemoveGeometryArray = [];
  55920. this._toRemoveMeshesArray = [];
  55921. }
  55922. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55923. if (!this._init)
  55924. return;
  55925. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55926. return;
  55927. position.divideToRef(collider._radius, this._scaledPosition);
  55928. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55929. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55930. var payload = {
  55931. collider: {
  55932. position: this._scaledPosition.asArray(),
  55933. velocity: this._scaledVelocity.asArray(),
  55934. radius: collider._radius.asArray()
  55935. },
  55936. collisionId: collisionIndex,
  55937. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55938. maximumRetry: maximumRetry
  55939. };
  55940. var message = {
  55941. payload: payload,
  55942. taskType: WorkerTaskType.COLLIDE
  55943. };
  55944. this._worker.postMessage(message);
  55945. };
  55946. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55947. this._scene = scene;
  55948. this._scene.registerAfterRender(this._afterRender);
  55949. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55950. this._worker = new Worker(workerUrl);
  55951. this._worker.onmessage = this._onMessageFromWorker;
  55952. var message = {
  55953. payload: {},
  55954. taskType: WorkerTaskType.INIT
  55955. };
  55956. this._worker.postMessage(message);
  55957. };
  55958. CollisionCoordinatorWorker.prototype.destroy = function () {
  55959. this._scene.unregisterAfterRender(this._afterRender);
  55960. this._worker.terminate();
  55961. };
  55962. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55963. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55964. this.onMeshUpdated(mesh);
  55965. };
  55966. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55967. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55968. };
  55969. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55970. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55971. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55972. this.onGeometryUpdated(geometry);
  55973. };
  55974. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55975. this._toRemoveGeometryArray.push(geometry.id);
  55976. };
  55977. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55978. var submeshes = [];
  55979. if (mesh.subMeshes) {
  55980. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55981. var boundingInfo = sm.getBoundingInfo();
  55982. return {
  55983. position: idx,
  55984. verticesStart: sm.verticesStart,
  55985. verticesCount: sm.verticesCount,
  55986. indexStart: sm.indexStart,
  55987. indexCount: sm.indexCount,
  55988. hasMaterial: !!sm.getMaterial(),
  55989. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55990. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55991. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55992. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55993. };
  55994. });
  55995. }
  55996. var geometryId = null;
  55997. if (mesh instanceof BABYLON.Mesh) {
  55998. var geometry = mesh.geometry;
  55999. geometryId = geometry ? geometry.id : null;
  56000. }
  56001. else if (mesh instanceof BABYLON.InstancedMesh) {
  56002. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56003. geometryId = geometry ? geometry.id : null;
  56004. }
  56005. var boundingInfo = mesh.getBoundingInfo();
  56006. return {
  56007. uniqueId: mesh.uniqueId,
  56008. id: mesh.id,
  56009. name: mesh.name,
  56010. geometryId: geometryId,
  56011. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56012. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56013. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56014. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56015. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56016. subMeshes: submeshes,
  56017. checkCollisions: mesh.checkCollisions
  56018. };
  56019. };
  56020. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56021. return {
  56022. id: geometry.id,
  56023. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56024. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56025. indices: new Uint32Array(geometry.getIndices() || []),
  56026. };
  56027. };
  56028. return CollisionCoordinatorWorker;
  56029. }());
  56030. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56031. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56032. function CollisionCoordinatorLegacy() {
  56033. this._scaledPosition = BABYLON.Vector3.Zero();
  56034. this._scaledVelocity = BABYLON.Vector3.Zero();
  56035. this._finalPosition = BABYLON.Vector3.Zero();
  56036. }
  56037. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56038. position.divideToRef(collider._radius, this._scaledPosition);
  56039. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56040. collider.collidedMesh = null;
  56041. collider._retry = 0;
  56042. collider._initialVelocity = this._scaledVelocity;
  56043. collider._initialPosition = this._scaledPosition;
  56044. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56045. this._finalPosition.multiplyInPlace(collider._radius);
  56046. //run the callback
  56047. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56048. };
  56049. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56050. this._scene = scene;
  56051. };
  56052. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56053. //Legacy need no destruction method.
  56054. };
  56055. //No update in legacy mode
  56056. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56057. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56058. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56059. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56060. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56061. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56062. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56063. if (excludedMesh === void 0) { excludedMesh = null; }
  56064. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56065. if (collider._retry >= maximumRetry) {
  56066. finalPosition.copyFrom(position);
  56067. return;
  56068. }
  56069. // Check if this is a mesh else camera or -1
  56070. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56071. collider._initialize(position, velocity, closeDistance);
  56072. // Check all meshes
  56073. for (var index = 0; index < this._scene.meshes.length; index++) {
  56074. var mesh = this._scene.meshes[index];
  56075. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56076. mesh._checkCollision(collider);
  56077. }
  56078. }
  56079. if (!collider.collisionFound) {
  56080. position.addToRef(velocity, finalPosition);
  56081. return;
  56082. }
  56083. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56084. collider._getResponse(position, velocity);
  56085. }
  56086. if (velocity.length() <= closeDistance) {
  56087. finalPosition.copyFrom(position);
  56088. return;
  56089. }
  56090. collider._retry++;
  56091. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56092. };
  56093. return CollisionCoordinatorLegacy;
  56094. }());
  56095. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56096. })(BABYLON || (BABYLON = {}));
  56097. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56098. var BABYLON;
  56099. (function (BABYLON) {
  56100. /**
  56101. * A particle represents one of the element emitted by a particle system.
  56102. * This is mainly define by its coordinates, direction, velocity and age.
  56103. */
  56104. var Particle = /** @class */ (function () {
  56105. /**
  56106. * Creates a new instance Particle
  56107. * @param particleSystem the particle system the particle belongs to
  56108. */
  56109. function Particle(
  56110. /**
  56111. * particleSystem the particle system the particle belongs to.
  56112. */
  56113. particleSystem) {
  56114. this.particleSystem = particleSystem;
  56115. /**
  56116. * The world position of the particle in the scene.
  56117. */
  56118. this.position = BABYLON.Vector3.Zero();
  56119. /**
  56120. * The world direction of the particle in the scene.
  56121. */
  56122. this.direction = BABYLON.Vector3.Zero();
  56123. /**
  56124. * The color of the particle.
  56125. */
  56126. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56127. /**
  56128. * The color change of the particle per step.
  56129. */
  56130. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56131. /**
  56132. * Defines how long will the life of the particle be.
  56133. */
  56134. this.lifeTime = 1.0;
  56135. /**
  56136. * The current age of the particle.
  56137. */
  56138. this.age = 0;
  56139. /**
  56140. * The current size of the particle.
  56141. */
  56142. this.size = 0;
  56143. /**
  56144. * The current angle of the particle.
  56145. */
  56146. this.angle = 0;
  56147. /**
  56148. * Defines how fast is the angle changing.
  56149. */
  56150. this.angularSpeed = 0;
  56151. /**
  56152. * Defines the cell index used by the particle to be rendered from a sprite.
  56153. */
  56154. this.cellIndex = 0;
  56155. this._currentFrameCounter = 0;
  56156. if (!this.particleSystem.isAnimationSheetEnabled) {
  56157. return;
  56158. }
  56159. this.updateCellInfoFromSystem();
  56160. }
  56161. Particle.prototype.updateCellInfoFromSystem = function () {
  56162. this.cellIndex = this.particleSystem.startSpriteCellID;
  56163. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56164. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56165. }
  56166. else {
  56167. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56168. }
  56169. };
  56170. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56171. // (ageOffset / scaledUpdateSpeed) / available cells
  56172. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56173. this._currentFrameCounter += scaledUpdateSpeed;
  56174. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56175. this._currentFrameCounter = 0;
  56176. this.cellIndex++;
  56177. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56178. this.cellIndex = this.particleSystem.endSpriteCellID;
  56179. }
  56180. }
  56181. };
  56182. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56183. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56184. this.cellIndex++;
  56185. this._currentFrameCounter = 0;
  56186. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56187. if (this.particleSystem.spriteCellLoop) {
  56188. this.cellIndex = this.particleSystem.startSpriteCellID;
  56189. }
  56190. else {
  56191. this.cellIndex = this.particleSystem.endSpriteCellID;
  56192. }
  56193. }
  56194. }
  56195. else {
  56196. this._currentFrameCounter++;
  56197. }
  56198. };
  56199. /**
  56200. * Copy the properties of particle to another one.
  56201. * @param other the particle to copy the information to.
  56202. */
  56203. Particle.prototype.copyTo = function (other) {
  56204. other.position.copyFrom(this.position);
  56205. other.direction.copyFrom(this.direction);
  56206. other.color.copyFrom(this.color);
  56207. other.colorStep.copyFrom(this.colorStep);
  56208. other.lifeTime = this.lifeTime;
  56209. other.age = this.age;
  56210. other.size = this.size;
  56211. other.angle = this.angle;
  56212. other.angularSpeed = this.angularSpeed;
  56213. other.particleSystem = this.particleSystem;
  56214. other.cellIndex = this.cellIndex;
  56215. };
  56216. return Particle;
  56217. }());
  56218. BABYLON.Particle = Particle;
  56219. })(BABYLON || (BABYLON = {}));
  56220. //# sourceMappingURL=babylon.particle.js.map
  56221. var BABYLON;
  56222. (function (BABYLON) {
  56223. /**
  56224. * This represents a particle system in Babylon.
  56225. * 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.
  56226. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56227. * @example https://doc.babylonjs.com/babylon101/particles
  56228. */
  56229. var ParticleSystem = /** @class */ (function () {
  56230. /**
  56231. * Instantiates a particle system.
  56232. * 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.
  56233. * @param name The name of the particle system
  56234. * @param capacity The max number of particles alive at the same time
  56235. * @param scene The scene the particle system belongs to
  56236. * @param customEffect a custom effect used to change the way particles are rendered by default
  56237. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56238. * @param epsilon Offset used to render the particles
  56239. */
  56240. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56241. if (customEffect === void 0) { customEffect = null; }
  56242. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56243. if (epsilon === void 0) { epsilon = 0.01; }
  56244. var _this = this;
  56245. /**
  56246. * List of animations used by the particle system.
  56247. */
  56248. this.animations = [];
  56249. /**
  56250. * The rendering group used by the Particle system to chose when to render.
  56251. */
  56252. this.renderingGroupId = 0;
  56253. /**
  56254. * The emitter represents the Mesh or position we are attaching the particle system to.
  56255. */
  56256. this.emitter = null;
  56257. /**
  56258. * The maximum number of particles to emit per frame
  56259. */
  56260. this.emitRate = 10;
  56261. /**
  56262. * If you want to launch only a few particles at once, that can be done, as well.
  56263. */
  56264. this.manualEmitCount = -1;
  56265. /**
  56266. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56267. */
  56268. this.updateSpeed = 0.01;
  56269. /**
  56270. * The amount of time the particle system is running (depends of the overall update speed).
  56271. */
  56272. this.targetStopDuration = 0;
  56273. /**
  56274. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56275. */
  56276. this.disposeOnStop = false;
  56277. /**
  56278. * Minimum power of emitting particles.
  56279. */
  56280. this.minEmitPower = 1;
  56281. /**
  56282. * Maximum power of emitting particles.
  56283. */
  56284. this.maxEmitPower = 1;
  56285. /**
  56286. * Minimum life time of emitting particles.
  56287. */
  56288. this.minLifeTime = 1;
  56289. /**
  56290. * Maximum life time of emitting particles.
  56291. */
  56292. this.maxLifeTime = 1;
  56293. /**
  56294. * Minimum Size of emitting particles.
  56295. */
  56296. this.minSize = 1;
  56297. /**
  56298. * Maximum Size of emitting particles.
  56299. */
  56300. this.maxSize = 1;
  56301. /**
  56302. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56303. */
  56304. this.minAngularSpeed = 0;
  56305. /**
  56306. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56307. */
  56308. this.maxAngularSpeed = 0;
  56309. /**
  56310. * The layer mask we are rendering the particles through.
  56311. */
  56312. this.layerMask = 0x0FFFFFFF;
  56313. /**
  56314. * This can help using your own shader to render the particle system.
  56315. * The according effect will be created
  56316. */
  56317. this.customShader = null;
  56318. /**
  56319. * By default particle system starts as soon as they are created. This prevents the
  56320. * automatic start to happen and let you decide when to start emitting particles.
  56321. */
  56322. this.preventAutoStart = false;
  56323. /**
  56324. * Callback triggered when the particle animation is ending.
  56325. */
  56326. this.onAnimationEnd = null;
  56327. /**
  56328. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56329. */
  56330. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56331. /**
  56332. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56333. * to override the particles.
  56334. */
  56335. this.forceDepthWrite = false;
  56336. /**
  56337. * You can use gravity if you want to give an orientation to your particles.
  56338. */
  56339. this.gravity = BABYLON.Vector3.Zero();
  56340. /**
  56341. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56342. */
  56343. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56344. /**
  56345. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56346. */
  56347. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56348. /**
  56349. * Color the particle will have at the end of its lifetime.
  56350. */
  56351. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56352. /**
  56353. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56354. */
  56355. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56356. /**
  56357. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56358. */
  56359. this.spriteCellLoop = true;
  56360. /**
  56361. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56362. */
  56363. this.spriteCellChangeSpeed = 0;
  56364. /**
  56365. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56366. */
  56367. this.startSpriteCellID = 0;
  56368. /**
  56369. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56370. */
  56371. this.endSpriteCellID = 0;
  56372. /**
  56373. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56374. */
  56375. this.spriteCellWidth = 0;
  56376. /**
  56377. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56378. */
  56379. this.spriteCellHeight = 0;
  56380. /**
  56381. * An event triggered when the system is disposed.
  56382. */
  56383. this.onDisposeObservable = new BABYLON.Observable();
  56384. this._particles = new Array();
  56385. this._stockParticles = new Array();
  56386. this._newPartsExcess = 0;
  56387. this._vertexBuffers = {};
  56388. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56389. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56390. this._scaledDirection = BABYLON.Vector3.Zero();
  56391. this._scaledGravity = BABYLON.Vector3.Zero();
  56392. this._currentRenderId = -1;
  56393. this._started = false;
  56394. this._stopped = false;
  56395. this._actualFrame = 0;
  56396. this._vertexBufferSize = 11;
  56397. // start of sub system methods
  56398. /**
  56399. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56400. * Its lifetime will start back at 0.
  56401. */
  56402. this.recycleParticle = function (particle) {
  56403. var lastParticle = _this._particles.pop();
  56404. if (lastParticle !== particle) {
  56405. lastParticle.copyTo(particle);
  56406. }
  56407. _this._stockParticles.push(lastParticle);
  56408. };
  56409. this._createParticle = function () {
  56410. var particle;
  56411. if (_this._stockParticles.length !== 0) {
  56412. particle = _this._stockParticles.pop();
  56413. particle.age = 0;
  56414. particle.cellIndex = _this.startSpriteCellID;
  56415. }
  56416. else {
  56417. particle = new BABYLON.Particle(_this);
  56418. }
  56419. return particle;
  56420. };
  56421. this._emitFromParticle = function (particle) {
  56422. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56423. return;
  56424. }
  56425. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56426. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56427. subSystem._rootParticleSystem = _this;
  56428. _this.activeSubSystems.push(subSystem);
  56429. subSystem.start();
  56430. };
  56431. this._appendParticleVertexes = null;
  56432. this.id = name;
  56433. this.name = name;
  56434. this._capacity = capacity;
  56435. this._epsilon = epsilon;
  56436. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56437. if (isAnimationSheetEnabled) {
  56438. this._vertexBufferSize = 12;
  56439. }
  56440. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56441. this._customEffect = customEffect;
  56442. scene.particleSystems.push(this);
  56443. this._createIndexBuffer();
  56444. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56445. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56446. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56447. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56448. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56449. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56450. if (this._isAnimationSheetEnabled) {
  56451. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56452. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56453. }
  56454. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56455. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56456. this._vertexBuffers["options"] = options;
  56457. // Default emitter type
  56458. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56459. this.updateFunction = function (particles) {
  56460. for (var index = 0; index < particles.length; index++) {
  56461. var particle = particles[index];
  56462. particle.age += _this._scaledUpdateSpeed;
  56463. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56464. _this._emitFromParticle(particle);
  56465. _this.recycleParticle(particle);
  56466. index--;
  56467. continue;
  56468. }
  56469. else {
  56470. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56471. particle.color.addInPlace(_this._scaledColorStep);
  56472. if (particle.color.a < 0)
  56473. particle.color.a = 0;
  56474. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56475. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56476. particle.position.addInPlace(_this._scaledDirection);
  56477. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56478. particle.direction.addInPlace(_this._scaledGravity);
  56479. if (_this._isAnimationSheetEnabled) {
  56480. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56481. }
  56482. }
  56483. }
  56484. };
  56485. }
  56486. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56487. /**
  56488. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56489. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56490. */
  56491. get: function () {
  56492. if (this.particleEmitterType.direction1) {
  56493. return this.particleEmitterType.direction1;
  56494. }
  56495. return BABYLON.Vector3.Zero();
  56496. },
  56497. set: function (value) {
  56498. if (this.particleEmitterType.direction1) {
  56499. this.particleEmitterType.direction1 = value;
  56500. }
  56501. },
  56502. enumerable: true,
  56503. configurable: true
  56504. });
  56505. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56506. /**
  56507. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56508. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56509. */
  56510. get: function () {
  56511. if (this.particleEmitterType.direction2) {
  56512. return this.particleEmitterType.direction2;
  56513. }
  56514. return BABYLON.Vector3.Zero();
  56515. },
  56516. set: function (value) {
  56517. if (this.particleEmitterType.direction2) {
  56518. this.particleEmitterType.direction2 = value;
  56519. }
  56520. },
  56521. enumerable: true,
  56522. configurable: true
  56523. });
  56524. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56525. /**
  56526. * 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.
  56527. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56528. */
  56529. get: function () {
  56530. if (this.particleEmitterType.minEmitBox) {
  56531. return this.particleEmitterType.minEmitBox;
  56532. }
  56533. return BABYLON.Vector3.Zero();
  56534. },
  56535. set: function (value) {
  56536. if (this.particleEmitterType.minEmitBox) {
  56537. this.particleEmitterType.minEmitBox = value;
  56538. }
  56539. },
  56540. enumerable: true,
  56541. configurable: true
  56542. });
  56543. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56544. /**
  56545. * 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.
  56546. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56547. */
  56548. get: function () {
  56549. if (this.particleEmitterType.maxEmitBox) {
  56550. return this.particleEmitterType.maxEmitBox;
  56551. }
  56552. return BABYLON.Vector3.Zero();
  56553. },
  56554. set: function (value) {
  56555. if (this.particleEmitterType.maxEmitBox) {
  56556. this.particleEmitterType.maxEmitBox = value;
  56557. }
  56558. },
  56559. enumerable: true,
  56560. configurable: true
  56561. });
  56562. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56563. /**
  56564. * Sets a callback that will be triggered when the system is disposed.
  56565. */
  56566. set: function (callback) {
  56567. if (this._onDisposeObserver) {
  56568. this.onDisposeObservable.remove(this._onDisposeObserver);
  56569. }
  56570. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56571. },
  56572. enumerable: true,
  56573. configurable: true
  56574. });
  56575. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56576. /**
  56577. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56578. */
  56579. get: function () {
  56580. return this._isAnimationSheetEnabled;
  56581. },
  56582. enumerable: true,
  56583. configurable: true
  56584. });
  56585. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56586. //end of Sub-emitter
  56587. /**
  56588. * Gets the current list of active particles
  56589. */
  56590. get: function () {
  56591. return this._particles;
  56592. },
  56593. enumerable: true,
  56594. configurable: true
  56595. });
  56596. /**
  56597. * Returns the string "ParticleSystem"
  56598. * @returns a string containing the class name
  56599. */
  56600. ParticleSystem.prototype.getClassName = function () {
  56601. return "ParticleSystem";
  56602. };
  56603. ParticleSystem.prototype._createIndexBuffer = function () {
  56604. var indices = [];
  56605. var index = 0;
  56606. for (var count = 0; count < this._capacity; count++) {
  56607. indices.push(index);
  56608. indices.push(index + 1);
  56609. indices.push(index + 2);
  56610. indices.push(index);
  56611. indices.push(index + 2);
  56612. indices.push(index + 3);
  56613. index += 4;
  56614. }
  56615. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56616. };
  56617. /**
  56618. * Gets the maximum number of particles active at the same time.
  56619. * @returns The max number of active particles.
  56620. */
  56621. ParticleSystem.prototype.getCapacity = function () {
  56622. return this._capacity;
  56623. };
  56624. /**
  56625. * Gets Wether there are still active particles in the system.
  56626. * @returns True if it is alive, otherwise false.
  56627. */
  56628. ParticleSystem.prototype.isAlive = function () {
  56629. return this._alive;
  56630. };
  56631. /**
  56632. * Gets Wether the system has been started.
  56633. * @returns True if it has been started, otherwise false.
  56634. */
  56635. ParticleSystem.prototype.isStarted = function () {
  56636. return this._started;
  56637. };
  56638. /**
  56639. * Starts the particle system and begins to emit.
  56640. */
  56641. ParticleSystem.prototype.start = function () {
  56642. this._started = true;
  56643. this._stopped = false;
  56644. this._actualFrame = 0;
  56645. if (this.subEmitters && this.subEmitters.length != 0) {
  56646. this.activeSubSystems = new Array();
  56647. }
  56648. };
  56649. /**
  56650. * Stops the particle system.
  56651. * @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.
  56652. */
  56653. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56654. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56655. this._stopped = true;
  56656. if (stopSubEmitters) {
  56657. this._stopSubEmitters();
  56658. }
  56659. };
  56660. // animation sheet
  56661. /**
  56662. * Remove all active particles
  56663. */
  56664. ParticleSystem.prototype.reset = function () {
  56665. this._stockParticles = [];
  56666. this._particles = [];
  56667. };
  56668. /**
  56669. * @hidden (for internal use only)
  56670. */
  56671. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56672. var offset = index * this._vertexBufferSize;
  56673. this._vertexData[offset] = particle.position.x;
  56674. this._vertexData[offset + 1] = particle.position.y;
  56675. this._vertexData[offset + 2] = particle.position.z;
  56676. this._vertexData[offset + 3] = particle.color.r;
  56677. this._vertexData[offset + 4] = particle.color.g;
  56678. this._vertexData[offset + 5] = particle.color.b;
  56679. this._vertexData[offset + 6] = particle.color.a;
  56680. this._vertexData[offset + 7] = particle.angle;
  56681. this._vertexData[offset + 8] = particle.size;
  56682. this._vertexData[offset + 9] = offsetX;
  56683. this._vertexData[offset + 10] = offsetY;
  56684. };
  56685. /**
  56686. * @hidden (for internal use only)
  56687. */
  56688. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56689. if (offsetX === 0)
  56690. offsetX = this._epsilon;
  56691. else if (offsetX === 1)
  56692. offsetX = 1 - this._epsilon;
  56693. if (offsetY === 0)
  56694. offsetY = this._epsilon;
  56695. else if (offsetY === 1)
  56696. offsetY = 1 - this._epsilon;
  56697. var offset = index * this._vertexBufferSize;
  56698. this._vertexData[offset] = particle.position.x;
  56699. this._vertexData[offset + 1] = particle.position.y;
  56700. this._vertexData[offset + 2] = particle.position.z;
  56701. this._vertexData[offset + 3] = particle.color.r;
  56702. this._vertexData[offset + 4] = particle.color.g;
  56703. this._vertexData[offset + 5] = particle.color.b;
  56704. this._vertexData[offset + 6] = particle.color.a;
  56705. this._vertexData[offset + 7] = particle.angle;
  56706. this._vertexData[offset + 8] = particle.size;
  56707. this._vertexData[offset + 9] = offsetX;
  56708. this._vertexData[offset + 10] = offsetY;
  56709. this._vertexData[offset + 11] = particle.cellIndex;
  56710. };
  56711. ParticleSystem.prototype._stopSubEmitters = function () {
  56712. if (!this.activeSubSystems) {
  56713. return;
  56714. }
  56715. this.activeSubSystems.forEach(function (subSystem) {
  56716. subSystem.stop(true);
  56717. });
  56718. this.activeSubSystems = new Array();
  56719. };
  56720. ParticleSystem.prototype._removeFromRoot = function () {
  56721. if (!this._rootParticleSystem) {
  56722. return;
  56723. }
  56724. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56725. if (index !== -1) {
  56726. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56727. }
  56728. };
  56729. // end of sub system methods
  56730. ParticleSystem.prototype._update = function (newParticles) {
  56731. // Update current
  56732. this._alive = this._particles.length > 0;
  56733. this.updateFunction(this._particles);
  56734. // Add new ones
  56735. var worldMatrix;
  56736. if (this.emitter.position) {
  56737. var emitterMesh = this.emitter;
  56738. worldMatrix = emitterMesh.getWorldMatrix();
  56739. }
  56740. else {
  56741. var emitterPosition = this.emitter;
  56742. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56743. }
  56744. var particle;
  56745. for (var index = 0; index < newParticles; index++) {
  56746. if (this._particles.length === this._capacity) {
  56747. break;
  56748. }
  56749. particle = this._createParticle();
  56750. this._particles.push(particle);
  56751. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56752. if (this.startPositionFunction) {
  56753. this.startPositionFunction(worldMatrix, particle.position, particle);
  56754. }
  56755. else {
  56756. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56757. }
  56758. if (this.startDirectionFunction) {
  56759. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56760. }
  56761. else {
  56762. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56763. }
  56764. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56765. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56766. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56767. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56768. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56769. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56770. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56771. }
  56772. };
  56773. ParticleSystem.prototype._getEffect = function () {
  56774. if (this._customEffect) {
  56775. return this._customEffect;
  56776. }
  56777. ;
  56778. var defines = [];
  56779. if (this._scene.clipPlane) {
  56780. defines.push("#define CLIPPLANE");
  56781. }
  56782. if (this._isAnimationSheetEnabled) {
  56783. defines.push("#define ANIMATESHEET");
  56784. }
  56785. // Effect
  56786. var join = defines.join("\n");
  56787. if (this._cachedDefines !== join) {
  56788. this._cachedDefines = join;
  56789. var attributesNamesOrOptions;
  56790. var effectCreationOption;
  56791. if (this._isAnimationSheetEnabled) {
  56792. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56793. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56794. }
  56795. else {
  56796. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56797. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56798. }
  56799. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56800. }
  56801. return this._effect;
  56802. };
  56803. /**
  56804. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56805. */
  56806. ParticleSystem.prototype.animate = function () {
  56807. if (!this._started)
  56808. return;
  56809. var effect = this._getEffect();
  56810. // Check
  56811. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56812. return;
  56813. if (this._currentRenderId === this._scene.getRenderId()) {
  56814. return;
  56815. }
  56816. this._currentRenderId = this._scene.getRenderId();
  56817. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56818. // determine the number of particles we need to create
  56819. var newParticles;
  56820. if (this.manualEmitCount > -1) {
  56821. newParticles = this.manualEmitCount;
  56822. this._newPartsExcess = 0;
  56823. this.manualEmitCount = 0;
  56824. }
  56825. else {
  56826. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56827. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56828. }
  56829. if (this._newPartsExcess > 1.0) {
  56830. newParticles += this._newPartsExcess >> 0;
  56831. this._newPartsExcess -= this._newPartsExcess >> 0;
  56832. }
  56833. this._alive = false;
  56834. if (!this._stopped) {
  56835. this._actualFrame += this._scaledUpdateSpeed;
  56836. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56837. this.stop();
  56838. }
  56839. else {
  56840. newParticles = 0;
  56841. }
  56842. this._update(newParticles);
  56843. // Stopped?
  56844. if (this._stopped) {
  56845. if (!this._alive) {
  56846. this._started = false;
  56847. if (this.onAnimationEnd) {
  56848. this.onAnimationEnd();
  56849. }
  56850. if (this.disposeOnStop) {
  56851. this._scene._toBeDisposed.push(this);
  56852. }
  56853. }
  56854. }
  56855. // Animation sheet
  56856. if (this._isAnimationSheetEnabled) {
  56857. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56858. }
  56859. else {
  56860. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56861. }
  56862. // Update VBO
  56863. var offset = 0;
  56864. for (var index = 0; index < this._particles.length; index++) {
  56865. var particle = this._particles[index];
  56866. this._appendParticleVertexes(offset, particle);
  56867. offset += 4;
  56868. }
  56869. if (this._vertexBuffer) {
  56870. this._vertexBuffer.update(this._vertexData);
  56871. }
  56872. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56873. this.stop();
  56874. }
  56875. };
  56876. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56877. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56878. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56879. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56880. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56881. };
  56882. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56883. this._appendParticleVertex(offset++, particle, 0, 0);
  56884. this._appendParticleVertex(offset++, particle, 1, 0);
  56885. this._appendParticleVertex(offset++, particle, 1, 1);
  56886. this._appendParticleVertex(offset++, particle, 0, 1);
  56887. };
  56888. /**
  56889. * Rebuilds the particle system.
  56890. */
  56891. ParticleSystem.prototype.rebuild = function () {
  56892. this._createIndexBuffer();
  56893. if (this._vertexBuffer) {
  56894. this._vertexBuffer._rebuild();
  56895. }
  56896. };
  56897. /**
  56898. * Is this system ready to be used/rendered
  56899. * @return true if the system is ready
  56900. */
  56901. ParticleSystem.prototype.isReady = function () {
  56902. var effect = this._getEffect();
  56903. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56904. return false;
  56905. }
  56906. return true;
  56907. };
  56908. /**
  56909. * Renders the particle system in its current state.
  56910. * @returns the current number of particles
  56911. */
  56912. ParticleSystem.prototype.render = function () {
  56913. var effect = this._getEffect();
  56914. // Check
  56915. if (!this.isReady() || !this._particles.length) {
  56916. return 0;
  56917. }
  56918. var engine = this._scene.getEngine();
  56919. // Render
  56920. engine.enableEffect(effect);
  56921. engine.setState(false);
  56922. var viewMatrix = this._scene.getViewMatrix();
  56923. effect.setTexture("diffuseSampler", this.particleTexture);
  56924. effect.setMatrix("view", viewMatrix);
  56925. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56926. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56927. var baseSize = this.particleTexture.getBaseSize();
  56928. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56929. }
  56930. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56931. if (this._scene.clipPlane) {
  56932. var clipPlane = this._scene.clipPlane;
  56933. var invView = viewMatrix.clone();
  56934. invView.invert();
  56935. effect.setMatrix("invView", invView);
  56936. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56937. }
  56938. // VBOs
  56939. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56940. // Draw order
  56941. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56942. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56943. }
  56944. else {
  56945. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56946. }
  56947. if (this.forceDepthWrite) {
  56948. engine.setDepthWrite(true);
  56949. }
  56950. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56951. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56952. return this._particles.length;
  56953. };
  56954. /**
  56955. * Disposes the particle system and free the associated resources
  56956. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56957. */
  56958. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56959. if (disposeTexture === void 0) { disposeTexture = true; }
  56960. if (this._vertexBuffer) {
  56961. this._vertexBuffer.dispose();
  56962. this._vertexBuffer = null;
  56963. }
  56964. if (this._indexBuffer) {
  56965. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56966. this._indexBuffer = null;
  56967. }
  56968. if (disposeTexture && this.particleTexture) {
  56969. this.particleTexture.dispose();
  56970. this.particleTexture = null;
  56971. }
  56972. this._removeFromRoot();
  56973. // Remove from scene
  56974. var index = this._scene.particleSystems.indexOf(this);
  56975. if (index > -1) {
  56976. this._scene.particleSystems.splice(index, 1);
  56977. }
  56978. // Callback
  56979. this.onDisposeObservable.notifyObservers(this);
  56980. this.onDisposeObservable.clear();
  56981. };
  56982. /**
  56983. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56984. * @param radius The radius of the sphere to emit from
  56985. * @returns the emitter
  56986. */
  56987. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56988. if (radius === void 0) { radius = 1; }
  56989. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56990. this.particleEmitterType = particleEmitter;
  56991. return particleEmitter;
  56992. };
  56993. /**
  56994. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56995. * @param radius The radius of the sphere to emit from
  56996. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56997. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56998. * @returns the emitter
  56999. */
  57000. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57001. if (radius === void 0) { radius = 1; }
  57002. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57003. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57004. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57005. this.particleEmitterType = particleEmitter;
  57006. return particleEmitter;
  57007. };
  57008. /**
  57009. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  57010. * @param radius The radius of the cone to emit from
  57011. * @param angle The base angle of the cone
  57012. * @returns the emitter
  57013. */
  57014. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57015. if (radius === void 0) { radius = 1; }
  57016. if (angle === void 0) { angle = Math.PI / 4; }
  57017. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57018. this.particleEmitterType = particleEmitter;
  57019. return particleEmitter;
  57020. };
  57021. // 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.
  57022. /**
  57023. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57024. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57025. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57026. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57027. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57028. * @returns the emitter
  57029. */
  57030. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57031. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57032. this.particleEmitterType = particleEmitter;
  57033. this.direction1 = direction1;
  57034. this.direction2 = direction2;
  57035. this.minEmitBox = minEmitBox;
  57036. this.maxEmitBox = maxEmitBox;
  57037. return particleEmitter;
  57038. };
  57039. // Clone
  57040. /**
  57041. * Clones the particle system.
  57042. * @param name The name of the cloned object
  57043. * @param newEmitter The new emitter to use
  57044. * @returns the cloned particle system
  57045. */
  57046. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57047. var custom = null;
  57048. var program = null;
  57049. if (this.customShader != null) {
  57050. program = this.customShader;
  57051. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57052. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57053. }
  57054. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57055. result.customShader = program;
  57056. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57057. if (newEmitter === undefined) {
  57058. newEmitter = this.emitter;
  57059. }
  57060. result.emitter = newEmitter;
  57061. if (this.particleTexture) {
  57062. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57063. }
  57064. if (!this.preventAutoStart) {
  57065. result.start();
  57066. }
  57067. return result;
  57068. };
  57069. /**
  57070. * Serializes the particle system to a JSON object.
  57071. * @returns the JSON object
  57072. */
  57073. ParticleSystem.prototype.serialize = function () {
  57074. var serializationObject = {};
  57075. serializationObject.name = this.name;
  57076. serializationObject.id = this.id;
  57077. // Emitter
  57078. if (this.emitter.position) {
  57079. var emitterMesh = this.emitter;
  57080. serializationObject.emitterId = emitterMesh.id;
  57081. }
  57082. else {
  57083. var emitterPosition = this.emitter;
  57084. serializationObject.emitter = emitterPosition.asArray();
  57085. }
  57086. serializationObject.capacity = this.getCapacity();
  57087. if (this.particleTexture) {
  57088. serializationObject.textureName = this.particleTexture.name;
  57089. }
  57090. // Animations
  57091. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57092. // Particle system
  57093. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57094. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57095. serializationObject.minSize = this.minSize;
  57096. serializationObject.maxSize = this.maxSize;
  57097. serializationObject.minEmitPower = this.minEmitPower;
  57098. serializationObject.maxEmitPower = this.maxEmitPower;
  57099. serializationObject.minLifeTime = this.minLifeTime;
  57100. serializationObject.maxLifeTime = this.maxLifeTime;
  57101. serializationObject.emitRate = this.emitRate;
  57102. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57103. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57104. serializationObject.gravity = this.gravity.asArray();
  57105. serializationObject.direction1 = this.direction1.asArray();
  57106. serializationObject.direction2 = this.direction2.asArray();
  57107. serializationObject.color1 = this.color1.asArray();
  57108. serializationObject.color2 = this.color2.asArray();
  57109. serializationObject.colorDead = this.colorDead.asArray();
  57110. serializationObject.updateSpeed = this.updateSpeed;
  57111. serializationObject.targetStopDuration = this.targetStopDuration;
  57112. serializationObject.textureMask = this.textureMask.asArray();
  57113. serializationObject.blendMode = this.blendMode;
  57114. serializationObject.customShader = this.customShader;
  57115. serializationObject.preventAutoStart = this.preventAutoStart;
  57116. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57117. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57118. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57119. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57120. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57121. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57122. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57123. // Emitter
  57124. if (this.particleEmitterType) {
  57125. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57126. }
  57127. return serializationObject;
  57128. };
  57129. /**
  57130. * Parses a JSON object to create a particle system.
  57131. * @param parsedParticleSystem The JSON object to parse
  57132. * @param scene The scene to create the particle system in
  57133. * @param rootUrl The root url to use to load external dependencies like texture
  57134. * @returns the Parsed particle system
  57135. */
  57136. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57137. var name = parsedParticleSystem.name;
  57138. var custom = null;
  57139. var program = null;
  57140. if (parsedParticleSystem.customShader) {
  57141. program = parsedParticleSystem.customShader;
  57142. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57143. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57144. }
  57145. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57146. particleSystem.customShader = program;
  57147. if (parsedParticleSystem.id) {
  57148. particleSystem.id = parsedParticleSystem.id;
  57149. }
  57150. // Auto start
  57151. if (parsedParticleSystem.preventAutoStart) {
  57152. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57153. }
  57154. // Texture
  57155. if (parsedParticleSystem.textureName) {
  57156. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57157. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57158. }
  57159. // Emitter
  57160. if (parsedParticleSystem.emitterId) {
  57161. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57162. }
  57163. else {
  57164. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57165. }
  57166. // Animations
  57167. if (parsedParticleSystem.animations) {
  57168. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57169. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57170. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57171. }
  57172. }
  57173. if (parsedParticleSystem.autoAnimate) {
  57174. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57175. }
  57176. // Particle system
  57177. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57178. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57179. particleSystem.minSize = parsedParticleSystem.minSize;
  57180. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57181. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57182. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57183. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57184. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57185. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57186. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57187. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57188. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57189. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57190. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57191. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57192. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57193. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57194. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57195. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57196. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57197. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57198. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57199. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57200. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57201. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57202. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57203. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57204. if (!particleSystem.preventAutoStart) {
  57205. particleSystem.start();
  57206. }
  57207. return particleSystem;
  57208. };
  57209. /**
  57210. * Source color is added to the destination color without alpha affecting the result.
  57211. */
  57212. ParticleSystem.BLENDMODE_ONEONE = 0;
  57213. /**
  57214. * Blend current color and particle color using particle’s alpha.
  57215. */
  57216. ParticleSystem.BLENDMODE_STANDARD = 1;
  57217. return ParticleSystem;
  57218. }());
  57219. BABYLON.ParticleSystem = ParticleSystem;
  57220. })(BABYLON || (BABYLON = {}));
  57221. //# sourceMappingURL=babylon.particleSystem.js.map
  57222. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57223. var BABYLON;
  57224. (function (BABYLON) {
  57225. /**
  57226. * Particle emitter emitting particles from the inside of a box.
  57227. * It emits the particles randomly between 2 given directions.
  57228. */
  57229. var BoxParticleEmitter = /** @class */ (function () {
  57230. /**
  57231. * Creates a new instance BoxParticleEmitter
  57232. */
  57233. function BoxParticleEmitter() {
  57234. /**
  57235. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57236. */
  57237. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57238. /**
  57239. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57240. */
  57241. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57242. /**
  57243. * 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.
  57244. */
  57245. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57246. /**
  57247. * 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.
  57248. */
  57249. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57250. }
  57251. /**
  57252. * Called by the particle System when the direction is computed for the created particle.
  57253. * @param emitPower is the power of the particle (speed)
  57254. * @param worldMatrix is the world matrix of the particle system
  57255. * @param directionToUpdate is the direction vector to update with the result
  57256. * @param particle is the particle we are computed the direction for
  57257. */
  57258. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57259. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57260. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57261. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57262. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57263. };
  57264. /**
  57265. * Called by the particle System when the position is computed for the created particle.
  57266. * @param worldMatrix is the world matrix of the particle system
  57267. * @param positionToUpdate is the position vector to update with the result
  57268. * @param particle is the particle we are computed the position for
  57269. */
  57270. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57271. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57272. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57273. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57274. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57275. };
  57276. /**
  57277. * Clones the current emitter and returns a copy of it
  57278. * @returns the new emitter
  57279. */
  57280. BoxParticleEmitter.prototype.clone = function () {
  57281. var newOne = new BoxParticleEmitter();
  57282. BABYLON.Tools.DeepCopy(this, newOne);
  57283. return newOne;
  57284. };
  57285. /**
  57286. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57287. * @param effect defines the update shader
  57288. */
  57289. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57290. effect.setVector3("direction1", this.direction1);
  57291. effect.setVector3("direction2", this.direction2);
  57292. effect.setVector3("minEmitBox", this.minEmitBox);
  57293. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57294. };
  57295. /**
  57296. * Returns a string to use to update the GPU particles update shader
  57297. * @returns a string containng the defines string
  57298. */
  57299. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57300. return "#define BOXEMITTER";
  57301. };
  57302. /**
  57303. * Returns the string "BoxEmitter"
  57304. * @returns a string containing the class name
  57305. */
  57306. BoxParticleEmitter.prototype.getClassName = function () {
  57307. return "BoxEmitter";
  57308. };
  57309. /**
  57310. * Serializes the particle system to a JSON object.
  57311. * @returns the JSON object
  57312. */
  57313. BoxParticleEmitter.prototype.serialize = function () {
  57314. var serializationObject = {};
  57315. serializationObject.type = this.getClassName();
  57316. serializationObject.direction1 = this.direction1.asArray();
  57317. serializationObject.direction2 = this.direction2.asArray();
  57318. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57319. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57320. return serializationObject;
  57321. };
  57322. /**
  57323. * Parse properties from a JSON object
  57324. * @param serializationObject defines the JSON object
  57325. */
  57326. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57327. this.direction1.copyFrom(serializationObject.direction1);
  57328. this.direction2.copyFrom(serializationObject.direction2);
  57329. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57330. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57331. };
  57332. return BoxParticleEmitter;
  57333. }());
  57334. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57335. })(BABYLON || (BABYLON = {}));
  57336. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57337. var BABYLON;
  57338. (function (BABYLON) {
  57339. /**
  57340. * Particle emitter emitting particles from the inside of a cone.
  57341. * It emits the particles alongside the cone volume from the base to the particle.
  57342. * The emission direction might be randomized.
  57343. */
  57344. var ConeParticleEmitter = /** @class */ (function () {
  57345. /**
  57346. * Creates a new instance ConeParticleEmitter
  57347. * @param radius the radius of the emission cone (1 by default)
  57348. * @param angles the cone base angle (PI by default)
  57349. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57350. */
  57351. function ConeParticleEmitter(radius,
  57352. /**
  57353. * The radius of the emission cone.
  57354. */
  57355. angle,
  57356. /**
  57357. * The cone base angle.
  57358. */
  57359. directionRandomizer) {
  57360. if (radius === void 0) { radius = 1; }
  57361. if (angle === void 0) { angle = Math.PI; }
  57362. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57363. this.angle = angle;
  57364. this.directionRandomizer = directionRandomizer;
  57365. this.radius = radius;
  57366. }
  57367. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57368. /**
  57369. * Gets the radius of the emission cone.
  57370. */
  57371. get: function () {
  57372. return this._radius;
  57373. },
  57374. /**
  57375. * Sets the radius of the emission cone.
  57376. */
  57377. set: function (value) {
  57378. this._radius = value;
  57379. if (this.angle !== 0) {
  57380. this._height = value / Math.tan(this.angle / 2);
  57381. }
  57382. else {
  57383. this._height = 1;
  57384. }
  57385. },
  57386. enumerable: true,
  57387. configurable: true
  57388. });
  57389. /**
  57390. * Called by the particle System when the direction is computed for the created particle.
  57391. * @param emitPower is the power of the particle (speed)
  57392. * @param worldMatrix is the world matrix of the particle system
  57393. * @param directionToUpdate is the direction vector to update with the result
  57394. * @param particle is the particle we are computed the direction for
  57395. */
  57396. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57397. if (this.angle === 0) {
  57398. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57399. }
  57400. else {
  57401. // measure the direction Vector from the emitter to the particle.
  57402. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57403. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57404. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57405. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57406. direction.x += randX;
  57407. direction.y += randY;
  57408. direction.z += randZ;
  57409. direction.normalize();
  57410. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57411. }
  57412. };
  57413. /**
  57414. * Called by the particle System when the position is computed for the created particle.
  57415. * @param worldMatrix is the world matrix of the particle system
  57416. * @param positionToUpdate is the position vector to update with the result
  57417. * @param particle is the particle we are computed the position for
  57418. */
  57419. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57420. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57421. var h = BABYLON.Scalar.RandomRange(0, 1);
  57422. // Better distribution in a cone at normal angles.
  57423. h = 1 - h * h;
  57424. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57425. radius = radius * h;
  57426. var randX = radius * Math.sin(s);
  57427. var randZ = radius * Math.cos(s);
  57428. var randY = h * this._height;
  57429. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57430. };
  57431. /**
  57432. * Clones the current emitter and returns a copy of it
  57433. * @returns the new emitter
  57434. */
  57435. ConeParticleEmitter.prototype.clone = function () {
  57436. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57437. BABYLON.Tools.DeepCopy(this, newOne);
  57438. return newOne;
  57439. };
  57440. /**
  57441. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57442. * @param effect defines the update shader
  57443. */
  57444. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57445. effect.setFloat("radius", this.radius);
  57446. effect.setFloat("coneAngle", this.angle);
  57447. effect.setFloat("height", this._height);
  57448. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57449. };
  57450. /**
  57451. * Returns a string to use to update the GPU particles update shader
  57452. * @returns a string containng the defines string
  57453. */
  57454. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57455. return "#define CONEEMITTER";
  57456. };
  57457. /**
  57458. * Returns the string "BoxEmitter"
  57459. * @returns a string containing the class name
  57460. */
  57461. ConeParticleEmitter.prototype.getClassName = function () {
  57462. return "ConeEmitter";
  57463. };
  57464. /**
  57465. * Serializes the particle system to a JSON object.
  57466. * @returns the JSON object
  57467. */
  57468. ConeParticleEmitter.prototype.serialize = function () {
  57469. var serializationObject = {};
  57470. serializationObject.type = this.getClassName();
  57471. serializationObject.radius = this.radius;
  57472. serializationObject.angle = this.angle;
  57473. serializationObject.directionRandomizer = this.directionRandomizer;
  57474. return serializationObject;
  57475. };
  57476. /**
  57477. * Parse properties from a JSON object
  57478. * @param serializationObject defines the JSON object
  57479. */
  57480. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57481. this.radius = serializationObject.radius;
  57482. this.angle = serializationObject.angle;
  57483. this.directionRandomizer = serializationObject.directionRandomizer;
  57484. };
  57485. return ConeParticleEmitter;
  57486. }());
  57487. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57488. })(BABYLON || (BABYLON = {}));
  57489. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57490. var BABYLON;
  57491. (function (BABYLON) {
  57492. /**
  57493. * Particle emitter emitting particles from the inside of a sphere.
  57494. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57495. */
  57496. var SphereParticleEmitter = /** @class */ (function () {
  57497. /**
  57498. * Creates a new instance SphereParticleEmitter
  57499. * @param radius the radius of the emission sphere (1 by default)
  57500. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57501. */
  57502. function SphereParticleEmitter(
  57503. /**
  57504. * The radius of the emission sphere.
  57505. */
  57506. radius,
  57507. /**
  57508. * How much to randomize the particle direction [0-1].
  57509. */
  57510. directionRandomizer) {
  57511. if (radius === void 0) { radius = 1; }
  57512. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57513. this.radius = radius;
  57514. this.directionRandomizer = directionRandomizer;
  57515. }
  57516. /**
  57517. * Called by the particle System when the direction is computed for the created particle.
  57518. * @param emitPower is the power of the particle (speed)
  57519. * @param worldMatrix is the world matrix of the particle system
  57520. * @param directionToUpdate is the direction vector to update with the result
  57521. * @param particle is the particle we are computed the direction for
  57522. */
  57523. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57524. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57525. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57526. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57527. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57528. direction.x += randX;
  57529. direction.y += randY;
  57530. direction.z += randZ;
  57531. direction.normalize();
  57532. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57533. };
  57534. /**
  57535. * Called by the particle System when the position is computed for the created particle.
  57536. * @param worldMatrix is the world matrix of the particle system
  57537. * @param positionToUpdate is the position vector to update with the result
  57538. * @param particle is the particle we are computed the position for
  57539. */
  57540. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57541. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57542. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57543. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57544. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57545. var randY = randRadius * Math.cos(theta);
  57546. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57547. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57548. };
  57549. /**
  57550. * Clones the current emitter and returns a copy of it
  57551. * @returns the new emitter
  57552. */
  57553. SphereParticleEmitter.prototype.clone = function () {
  57554. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57555. BABYLON.Tools.DeepCopy(this, newOne);
  57556. return newOne;
  57557. };
  57558. /**
  57559. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57560. * @param effect defines the update shader
  57561. */
  57562. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57563. effect.setFloat("radius", this.radius);
  57564. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57565. };
  57566. /**
  57567. * Returns a string to use to update the GPU particles update shader
  57568. * @returns a string containng the defines string
  57569. */
  57570. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57571. return "#define SPHEREEMITTER";
  57572. };
  57573. /**
  57574. * Returns the string "SphereParticleEmitter"
  57575. * @returns a string containing the class name
  57576. */
  57577. SphereParticleEmitter.prototype.getClassName = function () {
  57578. return "SphereParticleEmitter";
  57579. };
  57580. /**
  57581. * Serializes the particle system to a JSON object.
  57582. * @returns the JSON object
  57583. */
  57584. SphereParticleEmitter.prototype.serialize = function () {
  57585. var serializationObject = {};
  57586. serializationObject.type = this.getClassName();
  57587. serializationObject.radius = this.radius;
  57588. serializationObject.directionRandomizer = this.directionRandomizer;
  57589. return serializationObject;
  57590. };
  57591. /**
  57592. * Parse properties from a JSON object
  57593. * @param serializationObject defines the JSON object
  57594. */
  57595. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57596. this.radius = serializationObject.radius;
  57597. this.directionRandomizer = serializationObject.directionRandomizer;
  57598. };
  57599. return SphereParticleEmitter;
  57600. }());
  57601. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57602. /**
  57603. * Particle emitter emitting particles from the inside of a sphere.
  57604. * It emits the particles randomly between two vectors.
  57605. */
  57606. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57607. __extends(SphereDirectedParticleEmitter, _super);
  57608. /**
  57609. * Creates a new instance SphereDirectedParticleEmitter
  57610. * @param radius the radius of the emission sphere (1 by default)
  57611. * @param direction1 the min limit of the emission direction (up vector by default)
  57612. * @param direction2 the max limit of the emission direction (up vector by default)
  57613. */
  57614. function SphereDirectedParticleEmitter(radius,
  57615. /**
  57616. * The min limit of the emission direction.
  57617. */
  57618. direction1,
  57619. /**
  57620. * The max limit of the emission direction.
  57621. */
  57622. direction2) {
  57623. if (radius === void 0) { radius = 1; }
  57624. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57625. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57626. var _this = _super.call(this, radius) || this;
  57627. _this.direction1 = direction1;
  57628. _this.direction2 = direction2;
  57629. return _this;
  57630. }
  57631. /**
  57632. * Called by the particle System when the direction is computed for the created particle.
  57633. * @param emitPower is the power of the particle (speed)
  57634. * @param worldMatrix is the world matrix of the particle system
  57635. * @param directionToUpdate is the direction vector to update with the result
  57636. * @param particle is the particle we are computed the direction for
  57637. */
  57638. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57639. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57640. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57641. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57642. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57643. };
  57644. /**
  57645. * Clones the current emitter and returns a copy of it
  57646. * @returns the new emitter
  57647. */
  57648. SphereDirectedParticleEmitter.prototype.clone = function () {
  57649. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57650. BABYLON.Tools.DeepCopy(this, newOne);
  57651. return newOne;
  57652. };
  57653. /**
  57654. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57655. * @param effect defines the update shader
  57656. */
  57657. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57658. effect.setFloat("radius", this.radius);
  57659. effect.setVector3("direction1", this.direction1);
  57660. effect.setVector3("direction2", this.direction2);
  57661. };
  57662. /**
  57663. * Returns a string to use to update the GPU particles update shader
  57664. * @returns a string containng the defines string
  57665. */
  57666. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57667. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57668. };
  57669. /**
  57670. * Returns the string "SphereDirectedParticleEmitter"
  57671. * @returns a string containing the class name
  57672. */
  57673. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57674. return "SphereDirectedParticleEmitter";
  57675. };
  57676. /**
  57677. * Serializes the particle system to a JSON object.
  57678. * @returns the JSON object
  57679. */
  57680. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57681. var serializationObject = _super.prototype.serialize.call(this);
  57682. serializationObject.direction1 = this.direction1.asArray();
  57683. serializationObject.direction2 = this.direction2.asArray();
  57684. return serializationObject;
  57685. };
  57686. /**
  57687. * Parse properties from a JSON object
  57688. * @param serializationObject defines the JSON object
  57689. */
  57690. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57691. _super.prototype.parse.call(this, serializationObject);
  57692. this.direction1.copyFrom(serializationObject.direction1);
  57693. this.direction2.copyFrom(serializationObject.direction2);
  57694. };
  57695. return SphereDirectedParticleEmitter;
  57696. }(SphereParticleEmitter));
  57697. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57698. })(BABYLON || (BABYLON = {}));
  57699. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57700. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57701. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57702. s = arguments[i];
  57703. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57704. t[p] = s[p];
  57705. }
  57706. return t;
  57707. };
  57708. var BABYLON;
  57709. (function (BABYLON) {
  57710. /**
  57711. * This represents a GPU particle system in Babylon
  57712. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57713. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57714. */
  57715. var GPUParticleSystem = /** @class */ (function () {
  57716. /**
  57717. * Instantiates a GPU particle system.
  57718. * 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.
  57719. * @param name The name of the particle system
  57720. * @param capacity The max number of particles alive at the same time
  57721. * @param scene The scene the particle system belongs to
  57722. */
  57723. function GPUParticleSystem(name, options, scene) {
  57724. /**
  57725. * The emitter represents the Mesh or position we are attaching the particle system to.
  57726. */
  57727. this.emitter = null;
  57728. /**
  57729. * The rendering group used by the Particle system to chose when to render.
  57730. */
  57731. this.renderingGroupId = 0;
  57732. /**
  57733. * The layer mask we are rendering the particles through.
  57734. */
  57735. this.layerMask = 0x0FFFFFFF;
  57736. this._targetIndex = 0;
  57737. this._currentRenderId = -1;
  57738. this._started = false;
  57739. this._stopped = false;
  57740. this._timeDelta = 0;
  57741. this._attributesStrideSize = 16;
  57742. this._actualFrame = 0;
  57743. /**
  57744. * List of animations used by the particle system.
  57745. */
  57746. this.animations = [];
  57747. /**
  57748. * An event triggered when the system is disposed.
  57749. */
  57750. this.onDisposeObservable = new BABYLON.Observable();
  57751. /**
  57752. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57753. */
  57754. this.updateSpeed = 0.01;
  57755. /**
  57756. * The amount of time the particle system is running (depends of the overall update speed).
  57757. */
  57758. this.targetStopDuration = 0;
  57759. /**
  57760. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57761. */
  57762. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57763. /**
  57764. * Minimum life time of emitting particles.
  57765. */
  57766. this.minLifeTime = 1;
  57767. /**
  57768. * Maximum life time of emitting particles.
  57769. */
  57770. this.maxLifeTime = 1;
  57771. /**
  57772. * Minimum Size of emitting particles.
  57773. */
  57774. this.minSize = 1;
  57775. /**
  57776. * Maximum Size of emitting particles.
  57777. */
  57778. this.maxSize = 1;
  57779. /**
  57780. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57781. */
  57782. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57783. /**
  57784. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57785. */
  57786. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57787. /**
  57788. * Color the particle will have at the end of its lifetime.
  57789. */
  57790. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57791. /**
  57792. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57793. */
  57794. this.emitRate = 100;
  57795. /**
  57796. * You can use gravity if you want to give an orientation to your particles.
  57797. */
  57798. this.gravity = BABYLON.Vector3.Zero();
  57799. /**
  57800. * Minimum power of emitting particles.
  57801. */
  57802. this.minEmitPower = 1;
  57803. /**
  57804. * Maximum power of emitting particles.
  57805. */
  57806. this.maxEmitPower = 1;
  57807. /**
  57808. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57809. */
  57810. this.minAngularSpeed = 0;
  57811. /**
  57812. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57813. */
  57814. this.maxAngularSpeed = 0;
  57815. /**
  57816. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57817. * to override the particles.
  57818. */
  57819. this.forceDepthWrite = false;
  57820. this.id = name;
  57821. this.name = name;
  57822. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57823. this._engine = this._scene.getEngine();
  57824. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57825. this._capacity = fullOptions.capacity;
  57826. this._activeCount = fullOptions.capacity;
  57827. this._currentActiveCount = 0;
  57828. this._scene.particleSystems.push(this);
  57829. this._updateEffectOptions = {
  57830. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57831. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57832. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57833. "angleRange"],
  57834. uniformBuffersNames: [],
  57835. samplers: ["randomSampler"],
  57836. defines: "",
  57837. fallbacks: null,
  57838. onCompiled: null,
  57839. onError: null,
  57840. indexParameters: null,
  57841. maxSimultaneousLights: 0,
  57842. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57843. };
  57844. // Random data
  57845. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57846. var d = [];
  57847. for (var i = 0; i < maxTextureSize; ++i) {
  57848. d.push(Math.random());
  57849. d.push(Math.random());
  57850. d.push(Math.random());
  57851. d.push(Math.random());
  57852. }
  57853. 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);
  57854. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57855. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57856. this._randomTextureSize = maxTextureSize;
  57857. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57858. }
  57859. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57860. /**
  57861. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57862. */
  57863. get: function () {
  57864. if (!BABYLON.Engine.LastCreatedEngine) {
  57865. return false;
  57866. }
  57867. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57868. },
  57869. enumerable: true,
  57870. configurable: true
  57871. });
  57872. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57873. /**
  57874. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57875. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57876. */
  57877. get: function () {
  57878. if (this.particleEmitterType.direction1) {
  57879. return this.particleEmitterType.direction1;
  57880. }
  57881. return BABYLON.Vector3.Zero();
  57882. },
  57883. set: function (value) {
  57884. if (this.particleEmitterType.direction1) {
  57885. this.particleEmitterType.direction1 = value;
  57886. }
  57887. },
  57888. enumerable: true,
  57889. configurable: true
  57890. });
  57891. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57892. /**
  57893. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57894. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57895. */
  57896. get: function () {
  57897. if (this.particleEmitterType.direction2) {
  57898. return this.particleEmitterType.direction2;
  57899. }
  57900. return BABYLON.Vector3.Zero();
  57901. },
  57902. set: function (value) {
  57903. if (this.particleEmitterType.direction2) {
  57904. this.particleEmitterType.direction2 = value;
  57905. }
  57906. },
  57907. enumerable: true,
  57908. configurable: true
  57909. });
  57910. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57911. /**
  57912. * 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.
  57913. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57914. */
  57915. get: function () {
  57916. if (this.particleEmitterType.minEmitBox) {
  57917. return this.particleEmitterType.minEmitBox;
  57918. }
  57919. return BABYLON.Vector3.Zero();
  57920. },
  57921. set: function (value) {
  57922. if (this.particleEmitterType.minEmitBox) {
  57923. this.particleEmitterType.minEmitBox = value;
  57924. }
  57925. },
  57926. enumerable: true,
  57927. configurable: true
  57928. });
  57929. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57930. /**
  57931. * 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.
  57932. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57933. */
  57934. get: function () {
  57935. if (this.particleEmitterType.maxEmitBox) {
  57936. return this.particleEmitterType.maxEmitBox;
  57937. }
  57938. return BABYLON.Vector3.Zero();
  57939. },
  57940. set: function (value) {
  57941. if (this.particleEmitterType.maxEmitBox) {
  57942. this.particleEmitterType.maxEmitBox = value;
  57943. }
  57944. },
  57945. enumerable: true,
  57946. configurable: true
  57947. });
  57948. /**
  57949. * Gets the maximum number of particles active at the same time.
  57950. * @returns The max number of active particles.
  57951. */
  57952. GPUParticleSystem.prototype.getCapacity = function () {
  57953. return this._capacity;
  57954. };
  57955. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57956. /**
  57957. * Gets or set the number of active particles
  57958. */
  57959. get: function () {
  57960. return this._activeCount;
  57961. },
  57962. set: function (value) {
  57963. this._activeCount = Math.min(value, this._capacity);
  57964. },
  57965. enumerable: true,
  57966. configurable: true
  57967. });
  57968. /**
  57969. * Is this system ready to be used/rendered
  57970. * @return true if the system is ready
  57971. */
  57972. GPUParticleSystem.prototype.isReady = function () {
  57973. if (!this._updateEffect) {
  57974. this._recreateUpdateEffect();
  57975. this._recreateRenderEffect();
  57976. return false;
  57977. }
  57978. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57979. return false;
  57980. }
  57981. return true;
  57982. };
  57983. /**
  57984. * Gets Wether the system has been started.
  57985. * @returns True if it has been started, otherwise false.
  57986. */
  57987. GPUParticleSystem.prototype.isStarted = function () {
  57988. return this._started;
  57989. };
  57990. /**
  57991. * Starts the particle system and begins to emit.
  57992. */
  57993. GPUParticleSystem.prototype.start = function () {
  57994. this._started = true;
  57995. this._stopped = false;
  57996. };
  57997. /**
  57998. * Stops the particle system.
  57999. */
  58000. GPUParticleSystem.prototype.stop = function () {
  58001. this._stopped = true;
  58002. };
  58003. /**
  58004. * Remove all active particles
  58005. */
  58006. GPUParticleSystem.prototype.reset = function () {
  58007. this._releaseBuffers();
  58008. this._releaseVAOs();
  58009. this._currentActiveCount = 0;
  58010. this._targetIndex = 0;
  58011. };
  58012. /**
  58013. * Returns the string "GPUParticleSystem"
  58014. * @returns a string containing the class name
  58015. */
  58016. GPUParticleSystem.prototype.getClassName = function () {
  58017. return "GPUParticleSystem";
  58018. };
  58019. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  58020. var updateVertexBuffers = {};
  58021. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  58022. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  58023. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  58024. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  58025. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  58026. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  58027. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  58028. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  58029. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  58030. this._engine.bindArrayBuffer(null);
  58031. return vao;
  58032. };
  58033. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  58034. var renderVertexBuffers = {};
  58035. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  58036. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  58037. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  58038. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  58039. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  58040. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  58041. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  58042. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  58043. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  58044. this._engine.bindArrayBuffer(null);
  58045. return vao;
  58046. };
  58047. GPUParticleSystem.prototype._initialize = function (force) {
  58048. if (force === void 0) { force = false; }
  58049. if (this._buffer0 && !force) {
  58050. return;
  58051. }
  58052. var engine = this._scene.getEngine();
  58053. var data = new Array();
  58054. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  58055. // position
  58056. data.push(0.0);
  58057. data.push(0.0);
  58058. data.push(0.0);
  58059. // Age and life
  58060. data.push(0.0); // create the particle as a dead one to create a new one at start
  58061. data.push(0.0);
  58062. // Seed
  58063. data.push(Math.random());
  58064. // Size
  58065. data.push(0.0);
  58066. // color
  58067. data.push(0.0);
  58068. data.push(0.0);
  58069. data.push(0.0);
  58070. data.push(0.0);
  58071. // direction
  58072. data.push(0.0);
  58073. data.push(0.0);
  58074. data.push(0.0);
  58075. // angle
  58076. data.push(0.0);
  58077. data.push(0.0);
  58078. }
  58079. // Sprite data
  58080. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58081. -0.5, 0.5, 0, 1,
  58082. -0.5, -0.5, 0, 0,
  58083. 0.5, -0.5, 1, 0]);
  58084. // Buffers
  58085. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58086. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58087. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58088. // Update VAO
  58089. this._updateVAO = [];
  58090. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58091. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58092. // Render VAO
  58093. this._renderVAO = [];
  58094. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58095. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58096. // Links
  58097. this._sourceBuffer = this._buffer0;
  58098. this._targetBuffer = this._buffer1;
  58099. };
  58100. /** @hidden */
  58101. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58102. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58103. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58104. return;
  58105. }
  58106. this._updateEffectOptions.defines = defines;
  58107. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58108. };
  58109. /** @hidden */
  58110. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58111. var defines = "";
  58112. if (this._scene.clipPlane) {
  58113. defines = "\n#define CLIPPLANE";
  58114. }
  58115. if (this._renderEffect && this._renderEffect.defines === defines) {
  58116. return;
  58117. }
  58118. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58119. };
  58120. /**
  58121. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58122. */
  58123. GPUParticleSystem.prototype.animate = function () {
  58124. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58125. this._actualFrame += this._timeDelta;
  58126. if (!this._stopped) {
  58127. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58128. this.stop();
  58129. }
  58130. }
  58131. };
  58132. /**
  58133. * Renders the particle system in its current state.
  58134. * @returns the current number of particles
  58135. */
  58136. GPUParticleSystem.prototype.render = function () {
  58137. if (!this._started) {
  58138. return 0;
  58139. }
  58140. this._recreateUpdateEffect();
  58141. this._recreateRenderEffect();
  58142. if (!this.isReady()) {
  58143. return 0;
  58144. }
  58145. if (this._currentRenderId === this._scene.getRenderId()) {
  58146. return 0;
  58147. }
  58148. this._currentRenderId = this._scene.getRenderId();
  58149. // Get everything ready to render
  58150. this._initialize();
  58151. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58152. // Enable update effect
  58153. this._engine.enableEffect(this._updateEffect);
  58154. this._engine.setState(false);
  58155. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58156. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58157. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58158. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58159. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58160. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58161. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58162. this._updateEffect.setDirectColor4("color1", this.color1);
  58163. this._updateEffect.setDirectColor4("color2", this.color2);
  58164. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58165. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58166. this._updateEffect.setVector3("gravity", this.gravity);
  58167. if (this.particleEmitterType) {
  58168. this.particleEmitterType.applyToShader(this._updateEffect);
  58169. }
  58170. var emitterWM;
  58171. if (this.emitter.position) {
  58172. var emitterMesh = this.emitter;
  58173. emitterWM = emitterMesh.getWorldMatrix();
  58174. }
  58175. else {
  58176. var emitterPosition = this.emitter;
  58177. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58178. }
  58179. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58180. // Bind source VAO
  58181. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58182. // Update
  58183. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58184. this._engine.setRasterizerState(false);
  58185. this._engine.beginTransformFeedback();
  58186. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58187. this._engine.endTransformFeedback();
  58188. this._engine.setRasterizerState(true);
  58189. this._engine.bindTransformFeedbackBuffer(null);
  58190. // Enable render effect
  58191. this._engine.enableEffect(this._renderEffect);
  58192. var viewMatrix = this._scene.getViewMatrix();
  58193. this._renderEffect.setMatrix("view", viewMatrix);
  58194. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58195. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58196. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58197. if (this._scene.clipPlane) {
  58198. var clipPlane = this._scene.clipPlane;
  58199. var invView = viewMatrix.clone();
  58200. invView.invert();
  58201. this._renderEffect.setMatrix("invView", invView);
  58202. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58203. }
  58204. // Draw order
  58205. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58206. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58207. }
  58208. else {
  58209. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58210. }
  58211. if (this.forceDepthWrite) {
  58212. this._engine.setDepthWrite(true);
  58213. }
  58214. // Bind source VAO
  58215. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58216. // Render
  58217. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58218. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58219. // Switch VAOs
  58220. this._targetIndex++;
  58221. if (this._targetIndex === 2) {
  58222. this._targetIndex = 0;
  58223. }
  58224. // Switch buffers
  58225. var tmpBuffer = this._sourceBuffer;
  58226. this._sourceBuffer = this._targetBuffer;
  58227. this._targetBuffer = tmpBuffer;
  58228. return this._currentActiveCount;
  58229. };
  58230. /**
  58231. * Rebuilds the particle system
  58232. */
  58233. GPUParticleSystem.prototype.rebuild = function () {
  58234. this._initialize(true);
  58235. };
  58236. GPUParticleSystem.prototype._releaseBuffers = function () {
  58237. if (this._buffer0) {
  58238. this._buffer0.dispose();
  58239. this._buffer0 = null;
  58240. }
  58241. if (this._buffer1) {
  58242. this._buffer1.dispose();
  58243. this._buffer1 = null;
  58244. }
  58245. if (this._spriteBuffer) {
  58246. this._spriteBuffer.dispose();
  58247. this._spriteBuffer = null;
  58248. }
  58249. };
  58250. GPUParticleSystem.prototype._releaseVAOs = function () {
  58251. if (!this._updateVAO) {
  58252. return;
  58253. }
  58254. for (var index = 0; index < this._updateVAO.length; index++) {
  58255. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58256. }
  58257. this._updateVAO = [];
  58258. for (var index = 0; index < this._renderVAO.length; index++) {
  58259. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58260. }
  58261. this._renderVAO = [];
  58262. };
  58263. /**
  58264. * Disposes the particle system and free the associated resources
  58265. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58266. */
  58267. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58268. if (disposeTexture === void 0) { disposeTexture = true; }
  58269. var index = this._scene.particleSystems.indexOf(this);
  58270. if (index > -1) {
  58271. this._scene.particleSystems.splice(index, 1);
  58272. }
  58273. this._releaseBuffers();
  58274. this._releaseVAOs();
  58275. if (this._randomTexture) {
  58276. this._randomTexture.dispose();
  58277. this._randomTexture = null;
  58278. }
  58279. if (disposeTexture && this.particleTexture) {
  58280. this.particleTexture.dispose();
  58281. this.particleTexture = null;
  58282. }
  58283. // Callback
  58284. this.onDisposeObservable.notifyObservers(this);
  58285. this.onDisposeObservable.clear();
  58286. };
  58287. /**
  58288. * Clones the particle system.
  58289. * @param name The name of the cloned object
  58290. * @param newEmitter The new emitter to use
  58291. * @returns the cloned particle system
  58292. */
  58293. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58294. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58295. BABYLON.Tools.DeepCopy(this, result);
  58296. if (newEmitter === undefined) {
  58297. newEmitter = this.emitter;
  58298. }
  58299. result.emitter = newEmitter;
  58300. if (this.particleTexture) {
  58301. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58302. }
  58303. return result;
  58304. };
  58305. /**
  58306. * Serializes the particle system to a JSON object.
  58307. * @returns the JSON object
  58308. */
  58309. GPUParticleSystem.prototype.serialize = function () {
  58310. var serializationObject = {};
  58311. serializationObject.name = this.name;
  58312. serializationObject.id = this.id;
  58313. // Emitter
  58314. if (this.emitter.position) {
  58315. var emitterMesh = this.emitter;
  58316. serializationObject.emitterId = emitterMesh.id;
  58317. }
  58318. else {
  58319. var emitterPosition = this.emitter;
  58320. serializationObject.emitter = emitterPosition.asArray();
  58321. }
  58322. serializationObject.capacity = this.getCapacity();
  58323. if (this.particleTexture) {
  58324. serializationObject.textureName = this.particleTexture.name;
  58325. }
  58326. // Animations
  58327. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58328. // Particle system
  58329. serializationObject.activeParticleCount = this.activeParticleCount;
  58330. serializationObject.randomTextureSize = this._randomTextureSize;
  58331. serializationObject.minSize = this.minSize;
  58332. serializationObject.maxSize = this.maxSize;
  58333. serializationObject.minEmitPower = this.minEmitPower;
  58334. serializationObject.maxEmitPower = this.maxEmitPower;
  58335. serializationObject.minLifeTime = this.minLifeTime;
  58336. serializationObject.maxLifeTime = this.maxLifeTime;
  58337. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58338. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58339. serializationObject.emitRate = this.emitRate;
  58340. serializationObject.gravity = this.gravity.asArray();
  58341. serializationObject.color1 = this.color1.asArray();
  58342. serializationObject.color2 = this.color2.asArray();
  58343. serializationObject.colorDead = this.colorDead.asArray();
  58344. serializationObject.updateSpeed = this.updateSpeed;
  58345. serializationObject.targetStopDuration = this.targetStopDuration;
  58346. serializationObject.blendMode = this.blendMode;
  58347. // Emitter
  58348. if (this.particleEmitterType) {
  58349. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58350. }
  58351. return serializationObject;
  58352. };
  58353. /**
  58354. * Parses a JSON object to create a GPU particle system.
  58355. * @param parsedParticleSystem The JSON object to parse
  58356. * @param scene The scene to create the particle system in
  58357. * @param rootUrl The root url to use to load external dependencies like texture
  58358. * @returns the parsed GPU particle system
  58359. */
  58360. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58361. var name = parsedParticleSystem.name;
  58362. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58363. if (parsedParticleSystem.id) {
  58364. particleSystem.id = parsedParticleSystem.id;
  58365. }
  58366. // Texture
  58367. if (parsedParticleSystem.textureName) {
  58368. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58369. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58370. }
  58371. // Emitter
  58372. if (parsedParticleSystem.emitterId) {
  58373. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58374. }
  58375. else {
  58376. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58377. }
  58378. // Animations
  58379. if (parsedParticleSystem.animations) {
  58380. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58381. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58382. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58383. }
  58384. }
  58385. // Particle system
  58386. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58387. particleSystem.minSize = parsedParticleSystem.minSize;
  58388. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58389. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58390. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58391. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58392. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58393. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58394. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58395. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58396. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58397. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58398. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58399. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58400. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58401. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58402. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58403. // Emitter
  58404. if (parsedParticleSystem.particleEmitterType) {
  58405. var emitterType = void 0;
  58406. switch (parsedParticleSystem.particleEmitterType.type) {
  58407. case "SphereEmitter":
  58408. emitterType = new BABYLON.SphereParticleEmitter();
  58409. break;
  58410. case "SphereDirectedParticleEmitter":
  58411. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58412. break;
  58413. case "ConeEmitter":
  58414. emitterType = new BABYLON.ConeParticleEmitter();
  58415. break;
  58416. case "BoxEmitter":
  58417. default:
  58418. emitterType = new BABYLON.BoxParticleEmitter();
  58419. break;
  58420. }
  58421. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58422. particleSystem.particleEmitterType = emitterType;
  58423. }
  58424. return particleSystem;
  58425. };
  58426. return GPUParticleSystem;
  58427. }());
  58428. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58429. })(BABYLON || (BABYLON = {}));
  58430. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58431. var BABYLON;
  58432. (function (BABYLON) {
  58433. /**
  58434. * Represents one particle of a solid particle system.
  58435. */
  58436. var SolidParticle = /** @class */ (function () {
  58437. /**
  58438. * Creates a Solid Particle object.
  58439. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58440. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58441. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58442. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58443. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58444. * @param shapeId (integer) is the model shape identifier in the SPS.
  58445. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58446. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58447. */
  58448. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58449. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58450. /**
  58451. * particle global index
  58452. */
  58453. this.idx = 0;
  58454. /**
  58455. * The color of the particle
  58456. */
  58457. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58458. /**
  58459. * The world space position of the particle.
  58460. */
  58461. this.position = BABYLON.Vector3.Zero();
  58462. /**
  58463. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58464. */
  58465. this.rotation = BABYLON.Vector3.Zero();
  58466. /**
  58467. * The scaling of the particle.
  58468. */
  58469. this.scaling = BABYLON.Vector3.One();
  58470. /**
  58471. * The uvs of the particle.
  58472. */
  58473. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58474. /**
  58475. * The current speed of the particle.
  58476. */
  58477. this.velocity = BABYLON.Vector3.Zero();
  58478. /**
  58479. * The pivot point in the particle local space.
  58480. */
  58481. this.pivot = BABYLON.Vector3.Zero();
  58482. /**
  58483. * Must the particle be translated from its pivot point in its local space ?
  58484. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58485. * Default : false
  58486. */
  58487. this.translateFromPivot = false;
  58488. /**
  58489. * Is the particle active or not ?
  58490. */
  58491. this.alive = true;
  58492. /**
  58493. * Is the particle visible or not ?
  58494. */
  58495. this.isVisible = true;
  58496. /**
  58497. * Index of this particle in the global "positions" array (Internal use)
  58498. */
  58499. this._pos = 0;
  58500. /**
  58501. * Index of this particle in the global "indices" array (Internal use)
  58502. */
  58503. this._ind = 0;
  58504. /**
  58505. * ModelShape id of this particle
  58506. */
  58507. this.shapeId = 0;
  58508. /**
  58509. * Index of the particle in its shape id (Internal use)
  58510. */
  58511. this.idxInShape = 0;
  58512. /**
  58513. * Still set as invisible in order to skip useless computations (Internal use)
  58514. */
  58515. this._stillInvisible = false;
  58516. /**
  58517. * Last computed particle rotation matrix
  58518. */
  58519. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58520. /**
  58521. * Parent particle Id, if any.
  58522. * Default null.
  58523. */
  58524. this.parentId = null;
  58525. /**
  58526. * Internal global position in the SPS.
  58527. */
  58528. this._globalPosition = BABYLON.Vector3.Zero();
  58529. this.idx = particleIndex;
  58530. this._pos = positionIndex;
  58531. this._ind = indiceIndex;
  58532. this._model = model;
  58533. this.shapeId = shapeId;
  58534. this.idxInShape = idxInShape;
  58535. this._sps = sps;
  58536. if (modelBoundingInfo) {
  58537. this._modelBoundingInfo = modelBoundingInfo;
  58538. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58539. }
  58540. }
  58541. Object.defineProperty(SolidParticle.prototype, "scale", {
  58542. /**
  58543. * Legacy support, changed scale to scaling
  58544. */
  58545. get: function () {
  58546. return this.scaling;
  58547. },
  58548. /**
  58549. * Legacy support, changed scale to scaling
  58550. */
  58551. set: function (scale) {
  58552. this.scaling = scale;
  58553. },
  58554. enumerable: true,
  58555. configurable: true
  58556. });
  58557. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58558. /**
  58559. * Legacy support, changed quaternion to rotationQuaternion
  58560. */
  58561. get: function () {
  58562. return this.rotationQuaternion;
  58563. },
  58564. /**
  58565. * Legacy support, changed quaternion to rotationQuaternion
  58566. */
  58567. set: function (q) {
  58568. this.rotationQuaternion = q;
  58569. },
  58570. enumerable: true,
  58571. configurable: true
  58572. });
  58573. /**
  58574. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58575. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58576. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58577. * @returns true if it intersects
  58578. */
  58579. SolidParticle.prototype.intersectsMesh = function (target) {
  58580. if (!this._boundingInfo || !target._boundingInfo) {
  58581. return false;
  58582. }
  58583. if (this._sps._bSphereOnly) {
  58584. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58585. }
  58586. return this._boundingInfo.intersects(target._boundingInfo, false);
  58587. };
  58588. return SolidParticle;
  58589. }());
  58590. BABYLON.SolidParticle = SolidParticle;
  58591. /**
  58592. * Represents the shape of the model used by one particle of a solid particle system.
  58593. * SPS internal tool, don't use it manually.
  58594. */
  58595. var ModelShape = /** @class */ (function () {
  58596. /**
  58597. * 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.
  58598. * SPS internal tool, don't use it manually.
  58599. * @hidden
  58600. */
  58601. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58602. /**
  58603. * length of the shape in the model indices array (internal use)
  58604. */
  58605. this._indicesLength = 0;
  58606. this.shapeID = id;
  58607. this._shape = shape;
  58608. this._indicesLength = indicesLength;
  58609. this._shapeUV = shapeUV;
  58610. this._positionFunction = posFunction;
  58611. this._vertexFunction = vtxFunction;
  58612. }
  58613. return ModelShape;
  58614. }());
  58615. BABYLON.ModelShape = ModelShape;
  58616. /**
  58617. * Represents a Depth Sorted Particle in the solid particle system.
  58618. */
  58619. var DepthSortedParticle = /** @class */ (function () {
  58620. function DepthSortedParticle() {
  58621. /**
  58622. * Index of the particle in the "indices" array
  58623. */
  58624. this.ind = 0;
  58625. /**
  58626. * Length of the particle shape in the "indices" array
  58627. */
  58628. this.indicesLength = 0;
  58629. /**
  58630. * Squared distance from the particle to the camera
  58631. */
  58632. this.sqDistance = 0.0;
  58633. }
  58634. return DepthSortedParticle;
  58635. }());
  58636. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58637. })(BABYLON || (BABYLON = {}));
  58638. //# sourceMappingURL=babylon.solidParticle.js.map
  58639. var BABYLON;
  58640. (function (BABYLON) {
  58641. /**
  58642. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58643. *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.
  58644. * The SPS is also a particle system. It provides some methods to manage the particles.
  58645. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58646. *
  58647. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58648. */
  58649. var SolidParticleSystem = /** @class */ (function () {
  58650. /**
  58651. * Creates a SPS (Solid Particle System) object.
  58652. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58653. * @param scene (Scene) is the scene in which the SPS is added.
  58654. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58655. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58656. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58657. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58658. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58659. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58660. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58661. */
  58662. function SolidParticleSystem(name, scene, options) {
  58663. /**
  58664. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58665. * Example : var p = SPS.particles[i];
  58666. */
  58667. this.particles = new Array();
  58668. /**
  58669. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58670. */
  58671. this.nbParticles = 0;
  58672. /**
  58673. * If the particles must ever face the camera (default false). Useful for planar particles.
  58674. */
  58675. this.billboard = false;
  58676. /**
  58677. * Recompute normals when adding a shape
  58678. */
  58679. this.recomputeNormals = true;
  58680. /**
  58681. * This a counter ofr your own usage. It's not set by any SPS functions.
  58682. */
  58683. this.counter = 0;
  58684. /**
  58685. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58686. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58687. */
  58688. this.vars = {};
  58689. /**
  58690. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58691. */
  58692. this._bSphereOnly = false;
  58693. /**
  58694. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58695. */
  58696. this._bSphereRadiusFactor = 1.0;
  58697. this._positions = new Array();
  58698. this._indices = new Array();
  58699. this._normals = new Array();
  58700. this._colors = new Array();
  58701. this._uvs = new Array();
  58702. this._index = 0; // indices index
  58703. this._updatable = true;
  58704. this._pickable = false;
  58705. this._isVisibilityBoxLocked = false;
  58706. this._alwaysVisible = false;
  58707. this._depthSort = false;
  58708. this._shapeCounter = 0;
  58709. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58710. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58711. this._computeParticleColor = true;
  58712. this._computeParticleTexture = true;
  58713. this._computeParticleRotation = true;
  58714. this._computeParticleVertex = false;
  58715. this._computeBoundingBox = false;
  58716. this._depthSortParticles = true;
  58717. this._cam_axisZ = BABYLON.Vector3.Zero();
  58718. this._cam_axisY = BABYLON.Vector3.Zero();
  58719. this._cam_axisX = BABYLON.Vector3.Zero();
  58720. this._axisZ = BABYLON.Axis.Z;
  58721. this._camDir = BABYLON.Vector3.Zero();
  58722. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58723. this._rotMatrix = new BABYLON.Matrix();
  58724. this._invertMatrix = new BABYLON.Matrix();
  58725. this._rotated = BABYLON.Vector3.Zero();
  58726. this._quaternion = new BABYLON.Quaternion();
  58727. this._vertex = BABYLON.Vector3.Zero();
  58728. this._normal = BABYLON.Vector3.Zero();
  58729. this._yaw = 0.0;
  58730. this._pitch = 0.0;
  58731. this._roll = 0.0;
  58732. this._halfroll = 0.0;
  58733. this._halfpitch = 0.0;
  58734. this._halfyaw = 0.0;
  58735. this._sinRoll = 0.0;
  58736. this._cosRoll = 0.0;
  58737. this._sinPitch = 0.0;
  58738. this._cosPitch = 0.0;
  58739. this._sinYaw = 0.0;
  58740. this._cosYaw = 0.0;
  58741. this._mustUnrotateFixedNormals = false;
  58742. this._minimum = BABYLON.Vector3.Zero();
  58743. this._maximum = BABYLON.Vector3.Zero();
  58744. this._minBbox = BABYLON.Vector3.Zero();
  58745. this._maxBbox = BABYLON.Vector3.Zero();
  58746. this._particlesIntersect = false;
  58747. this._depthSortFunction = function (p1, p2) {
  58748. return (p2.sqDistance - p1.sqDistance);
  58749. };
  58750. this._needs32Bits = false;
  58751. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58752. this._scaledPivot = BABYLON.Vector3.Zero();
  58753. this._particleHasParent = false;
  58754. this.name = name;
  58755. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58756. this._camera = scene.activeCamera;
  58757. this._pickable = options ? options.isPickable : false;
  58758. this._depthSort = options ? options.enableDepthSort : false;
  58759. this._particlesIntersect = options ? options.particleIntersection : false;
  58760. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58761. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58762. if (options && options.updatable) {
  58763. this._updatable = options.updatable;
  58764. }
  58765. else {
  58766. this._updatable = true;
  58767. }
  58768. if (this._pickable) {
  58769. this.pickedParticles = [];
  58770. }
  58771. if (this._depthSort) {
  58772. this.depthSortedParticles = [];
  58773. }
  58774. }
  58775. /**
  58776. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58777. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58778. * @returns the created mesh
  58779. */
  58780. SolidParticleSystem.prototype.buildMesh = function () {
  58781. if (this.nbParticles === 0) {
  58782. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58783. this.addShape(triangle, 1);
  58784. triangle.dispose();
  58785. }
  58786. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58787. this._positions32 = new Float32Array(this._positions);
  58788. this._uvs32 = new Float32Array(this._uvs);
  58789. this._colors32 = new Float32Array(this._colors);
  58790. if (this.recomputeNormals) {
  58791. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58792. }
  58793. this._normals32 = new Float32Array(this._normals);
  58794. this._fixedNormal32 = new Float32Array(this._normals);
  58795. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58796. this._unrotateFixedNormals();
  58797. }
  58798. var vertexData = new BABYLON.VertexData();
  58799. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58800. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58801. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58802. if (this._uvs32.length > 0) {
  58803. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58804. }
  58805. if (this._colors32.length > 0) {
  58806. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58807. }
  58808. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58809. vertexData.applyToMesh(mesh, this._updatable);
  58810. this.mesh = mesh;
  58811. this.mesh.isPickable = this._pickable;
  58812. // free memory
  58813. if (!this._depthSort) {
  58814. this._indices = null;
  58815. }
  58816. this._positions = null;
  58817. this._normals = null;
  58818. this._uvs = null;
  58819. this._colors = null;
  58820. if (!this._updatable) {
  58821. this.particles.length = 0;
  58822. }
  58823. return mesh;
  58824. };
  58825. /**
  58826. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58827. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58828. * Thus the particles generated from `digest()` have their property `position` set yet.
  58829. * @param mesh ( Mesh ) is the mesh to be digested
  58830. * @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
  58831. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58832. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58833. * @returns the current SPS
  58834. */
  58835. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58836. var size = (options && options.facetNb) || 1;
  58837. var number = (options && options.number) || 0;
  58838. var delta = (options && options.delta) || 0;
  58839. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58840. var meshInd = mesh.getIndices();
  58841. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58842. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58843. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58844. var f = 0; // facet counter
  58845. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58846. // compute size from number
  58847. if (number) {
  58848. number = (number > totalFacets) ? totalFacets : number;
  58849. size = Math.round(totalFacets / number);
  58850. delta = 0;
  58851. }
  58852. else {
  58853. size = (size > totalFacets) ? totalFacets : size;
  58854. }
  58855. var facetPos = []; // submesh positions
  58856. var facetInd = []; // submesh indices
  58857. var facetUV = []; // submesh UV
  58858. var facetCol = []; // submesh colors
  58859. var barycenter = BABYLON.Vector3.Zero();
  58860. var sizeO = size;
  58861. while (f < totalFacets) {
  58862. size = sizeO + Math.floor((1 + delta) * Math.random());
  58863. if (f > totalFacets - size) {
  58864. size = totalFacets - f;
  58865. }
  58866. // reset temp arrays
  58867. facetPos.length = 0;
  58868. facetInd.length = 0;
  58869. facetUV.length = 0;
  58870. facetCol.length = 0;
  58871. // iterate over "size" facets
  58872. var fi = 0;
  58873. for (var j = f * 3; j < (f + size) * 3; j++) {
  58874. facetInd.push(fi);
  58875. var i = meshInd[j];
  58876. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58877. if (meshUV) {
  58878. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58879. }
  58880. if (meshCol) {
  58881. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58882. }
  58883. fi++;
  58884. }
  58885. // create a model shape for each single particle
  58886. var idx = this.nbParticles;
  58887. var shape = this._posToShape(facetPos);
  58888. var shapeUV = this._uvsToShapeUV(facetUV);
  58889. // compute the barycenter of the shape
  58890. var v;
  58891. for (v = 0; v < shape.length; v++) {
  58892. barycenter.addInPlace(shape[v]);
  58893. }
  58894. barycenter.scaleInPlace(1 / shape.length);
  58895. // shift the shape from its barycenter to the origin
  58896. for (v = 0; v < shape.length; v++) {
  58897. shape[v].subtractInPlace(barycenter);
  58898. }
  58899. var bInfo;
  58900. if (this._particlesIntersect) {
  58901. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58902. }
  58903. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58904. // add the particle in the SPS
  58905. var currentPos = this._positions.length;
  58906. var currentInd = this._indices.length;
  58907. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58908. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58909. // initialize the particle position
  58910. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58911. this._index += shape.length;
  58912. idx++;
  58913. this.nbParticles++;
  58914. this._shapeCounter++;
  58915. f += size;
  58916. }
  58917. return this;
  58918. };
  58919. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58920. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58921. var index = 0;
  58922. var idx = 0;
  58923. for (var p = 0; p < this.particles.length; p++) {
  58924. this._particle = this.particles[p];
  58925. this._shape = this._particle._model._shape;
  58926. if (this._particle.rotationQuaternion) {
  58927. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58928. }
  58929. else {
  58930. this._yaw = this._particle.rotation.y;
  58931. this._pitch = this._particle.rotation.x;
  58932. this._roll = this._particle.rotation.z;
  58933. this._quaternionRotationYPR();
  58934. }
  58935. this._quaternionToRotationMatrix();
  58936. this._rotMatrix.invertToRef(this._invertMatrix);
  58937. for (var pt = 0; pt < this._shape.length; pt++) {
  58938. idx = index + pt * 3;
  58939. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58940. this._fixedNormal32[idx] = this._normal.x;
  58941. this._fixedNormal32[idx + 1] = this._normal.y;
  58942. this._fixedNormal32[idx + 2] = this._normal.z;
  58943. }
  58944. index = idx + 3;
  58945. }
  58946. };
  58947. //reset copy
  58948. SolidParticleSystem.prototype._resetCopy = function () {
  58949. this._copy.position.x = 0;
  58950. this._copy.position.y = 0;
  58951. this._copy.position.z = 0;
  58952. this._copy.rotation.x = 0;
  58953. this._copy.rotation.y = 0;
  58954. this._copy.rotation.z = 0;
  58955. this._copy.rotationQuaternion = null;
  58956. this._copy.scaling.x = 1.0;
  58957. this._copy.scaling.y = 1.0;
  58958. this._copy.scaling.z = 1.0;
  58959. this._copy.uvs.x = 0;
  58960. this._copy.uvs.y = 0;
  58961. this._copy.uvs.z = 1.0;
  58962. this._copy.uvs.w = 1.0;
  58963. this._copy.color = null;
  58964. this._copy.translateFromPivot = false;
  58965. };
  58966. // _meshBuilder : inserts the shape model in the global SPS mesh
  58967. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58968. var i;
  58969. var u = 0;
  58970. var c = 0;
  58971. var n = 0;
  58972. this._resetCopy();
  58973. if (options && options.positionFunction) { // call to custom positionFunction
  58974. options.positionFunction(this._copy, idx, idxInShape);
  58975. this._mustUnrotateFixedNormals = true;
  58976. }
  58977. if (this._copy.rotationQuaternion) {
  58978. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58979. }
  58980. else {
  58981. this._yaw = this._copy.rotation.y;
  58982. this._pitch = this._copy.rotation.x;
  58983. this._roll = this._copy.rotation.z;
  58984. this._quaternionRotationYPR();
  58985. }
  58986. this._quaternionToRotationMatrix();
  58987. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58988. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58989. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58990. if (this._copy.translateFromPivot) {
  58991. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58992. }
  58993. else {
  58994. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58995. }
  58996. for (i = 0; i < shape.length; i++) {
  58997. this._vertex.x = shape[i].x;
  58998. this._vertex.y = shape[i].y;
  58999. this._vertex.z = shape[i].z;
  59000. if (options && options.vertexFunction) {
  59001. options.vertexFunction(this._copy, this._vertex, i);
  59002. }
  59003. this._vertex.x *= this._copy.scaling.x;
  59004. this._vertex.y *= this._copy.scaling.y;
  59005. this._vertex.z *= this._copy.scaling.z;
  59006. this._vertex.x -= this._scaledPivot.x;
  59007. this._vertex.y -= this._scaledPivot.y;
  59008. this._vertex.z -= this._scaledPivot.z;
  59009. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59010. this._rotated.addInPlace(this._pivotBackTranslation);
  59011. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  59012. if (meshUV) {
  59013. 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);
  59014. u += 2;
  59015. }
  59016. if (this._copy.color) {
  59017. this._color = this._copy.color;
  59018. }
  59019. else if (meshCol && meshCol[c] !== undefined) {
  59020. this._color.r = meshCol[c];
  59021. this._color.g = meshCol[c + 1];
  59022. this._color.b = meshCol[c + 2];
  59023. this._color.a = meshCol[c + 3];
  59024. }
  59025. else {
  59026. this._color.r = 1.0;
  59027. this._color.g = 1.0;
  59028. this._color.b = 1.0;
  59029. this._color.a = 1.0;
  59030. }
  59031. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  59032. c += 4;
  59033. if (!this.recomputeNormals && meshNor) {
  59034. this._normal.x = meshNor[n];
  59035. this._normal.y = meshNor[n + 1];
  59036. this._normal.z = meshNor[n + 2];
  59037. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  59038. normals.push(this._normal.x, this._normal.y, this._normal.z);
  59039. n += 3;
  59040. }
  59041. }
  59042. for (i = 0; i < meshInd.length; i++) {
  59043. var current_ind = p + meshInd[i];
  59044. indices.push(current_ind);
  59045. if (current_ind > 65535) {
  59046. this._needs32Bits = true;
  59047. }
  59048. }
  59049. if (this._pickable) {
  59050. var nbfaces = meshInd.length / 3;
  59051. for (i = 0; i < nbfaces; i++) {
  59052. this.pickedParticles.push({ idx: idx, faceId: i });
  59053. }
  59054. }
  59055. if (this._depthSort) {
  59056. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  59057. }
  59058. return this._copy;
  59059. };
  59060. // returns a shape array from positions array
  59061. SolidParticleSystem.prototype._posToShape = function (positions) {
  59062. var shape = [];
  59063. for (var i = 0; i < positions.length; i += 3) {
  59064. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59065. }
  59066. return shape;
  59067. };
  59068. // returns a shapeUV array from a Vector4 uvs
  59069. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59070. var shapeUV = [];
  59071. if (uvs) {
  59072. for (var i = 0; i < uvs.length; i++)
  59073. shapeUV.push(uvs[i]);
  59074. }
  59075. return shapeUV;
  59076. };
  59077. // adds a new particle object in the particles array
  59078. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59079. if (bInfo === void 0) { bInfo = null; }
  59080. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59081. this.particles.push(sp);
  59082. return sp;
  59083. };
  59084. /**
  59085. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59086. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59087. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59088. * @param nb (positive integer) the number of particles to be created from this model
  59089. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59090. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59091. * @returns the number of shapes in the system
  59092. */
  59093. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59094. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59095. var meshInd = mesh.getIndices();
  59096. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59097. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59098. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59099. var bbInfo;
  59100. if (this._particlesIntersect) {
  59101. bbInfo = mesh.getBoundingInfo();
  59102. }
  59103. var shape = this._posToShape(meshPos);
  59104. var shapeUV = this._uvsToShapeUV(meshUV);
  59105. var posfunc = options ? options.positionFunction : null;
  59106. var vtxfunc = options ? options.vertexFunction : null;
  59107. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59108. // particles
  59109. var sp;
  59110. var currentCopy;
  59111. var idx = this.nbParticles;
  59112. for (var i = 0; i < nb; i++) {
  59113. var currentPos = this._positions.length;
  59114. var currentInd = this._indices.length;
  59115. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59116. if (this._updatable) {
  59117. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59118. sp.position.copyFrom(currentCopy.position);
  59119. sp.rotation.copyFrom(currentCopy.rotation);
  59120. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59121. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59122. }
  59123. if (currentCopy.color && sp.color) {
  59124. sp.color.copyFrom(currentCopy.color);
  59125. }
  59126. sp.scaling.copyFrom(currentCopy.scaling);
  59127. sp.uvs.copyFrom(currentCopy.uvs);
  59128. }
  59129. this._index += shape.length;
  59130. idx++;
  59131. }
  59132. this.nbParticles += nb;
  59133. this._shapeCounter++;
  59134. return this._shapeCounter - 1;
  59135. };
  59136. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59137. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59138. this._resetCopy();
  59139. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59140. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59141. }
  59142. if (this._copy.rotationQuaternion) {
  59143. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59144. }
  59145. else {
  59146. this._yaw = this._copy.rotation.y;
  59147. this._pitch = this._copy.rotation.x;
  59148. this._roll = this._copy.rotation.z;
  59149. this._quaternionRotationYPR();
  59150. }
  59151. this._quaternionToRotationMatrix();
  59152. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59153. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59154. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59155. if (this._copy.translateFromPivot) {
  59156. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59157. }
  59158. else {
  59159. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59160. }
  59161. this._shape = particle._model._shape;
  59162. for (var pt = 0; pt < this._shape.length; pt++) {
  59163. this._vertex.x = this._shape[pt].x;
  59164. this._vertex.y = this._shape[pt].y;
  59165. this._vertex.z = this._shape[pt].z;
  59166. if (particle._model._vertexFunction) {
  59167. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59168. }
  59169. this._vertex.x *= this._copy.scaling.x;
  59170. this._vertex.y *= this._copy.scaling.y;
  59171. this._vertex.z *= this._copy.scaling.z;
  59172. this._vertex.x -= this._scaledPivot.x;
  59173. this._vertex.y -= this._scaledPivot.y;
  59174. this._vertex.z -= this._scaledPivot.z;
  59175. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59176. this._rotated.addInPlace(this._pivotBackTranslation);
  59177. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59178. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59179. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59180. }
  59181. particle.position.x = 0.0;
  59182. particle.position.y = 0.0;
  59183. particle.position.z = 0.0;
  59184. particle.rotation.x = 0.0;
  59185. particle.rotation.y = 0.0;
  59186. particle.rotation.z = 0.0;
  59187. particle.rotationQuaternion = null;
  59188. particle.scaling.x = 1.0;
  59189. particle.scaling.y = 1.0;
  59190. particle.scaling.z = 1.0;
  59191. particle.uvs.x = 0.0;
  59192. particle.uvs.y = 0.0;
  59193. particle.uvs.z = 1.0;
  59194. particle.uvs.w = 1.0;
  59195. particle.pivot.x = 0.0;
  59196. particle.pivot.y = 0.0;
  59197. particle.pivot.z = 0.0;
  59198. particle.translateFromPivot = false;
  59199. particle.parentId = null;
  59200. };
  59201. /**
  59202. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59203. * @returns the SPS.
  59204. */
  59205. SolidParticleSystem.prototype.rebuildMesh = function () {
  59206. for (var p = 0; p < this.particles.length; p++) {
  59207. this._rebuildParticle(this.particles[p]);
  59208. }
  59209. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59210. return this;
  59211. };
  59212. /**
  59213. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59214. * This method calls `updateParticle()` for each particle of the SPS.
  59215. * For an animated SPS, it is usually called within the render loop.
  59216. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59217. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59218. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59219. * @returns the SPS.
  59220. */
  59221. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59222. if (start === void 0) { start = 0; }
  59223. if (end === void 0) { end = this.nbParticles - 1; }
  59224. if (update === void 0) { update = true; }
  59225. if (!this._updatable) {
  59226. return this;
  59227. }
  59228. // custom beforeUpdate
  59229. this.beforeUpdateParticles(start, end, update);
  59230. this._cam_axisX.x = 1.0;
  59231. this._cam_axisX.y = 0.0;
  59232. this._cam_axisX.z = 0.0;
  59233. this._cam_axisY.x = 0.0;
  59234. this._cam_axisY.y = 1.0;
  59235. this._cam_axisY.z = 0.0;
  59236. this._cam_axisZ.x = 0.0;
  59237. this._cam_axisZ.y = 0.0;
  59238. this._cam_axisZ.z = 1.0;
  59239. // cases when the World Matrix is to be computed first
  59240. if (this.billboard || this._depthSort) {
  59241. this.mesh.computeWorldMatrix(true);
  59242. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59243. }
  59244. // if the particles will always face the camera
  59245. if (this.billboard) {
  59246. // compute the camera position and un-rotate it by the current mesh rotation
  59247. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59248. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59249. this._cam_axisZ.normalize();
  59250. // same for camera up vector extracted from the cam view matrix
  59251. var view = this._camera.getViewMatrix(true);
  59252. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59253. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59254. this._cam_axisY.normalize();
  59255. this._cam_axisX.normalize();
  59256. }
  59257. // if depthSort, compute the camera global position in the mesh local system
  59258. if (this._depthSort) {
  59259. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59260. }
  59261. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59262. var idx = 0; // current position index in the global array positions32
  59263. var index = 0; // position start index in the global array positions32 of the current particle
  59264. var colidx = 0; // current color index in the global array colors32
  59265. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59266. var uvidx = 0; // current uv index in the global array uvs32
  59267. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59268. var pt = 0; // current index in the particle model shape
  59269. if (this.mesh.isFacetDataEnabled) {
  59270. this._computeBoundingBox = true;
  59271. }
  59272. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59273. if (this._computeBoundingBox) {
  59274. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59275. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59276. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59277. }
  59278. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59279. if (this.mesh._boundingInfo) {
  59280. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59281. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59282. }
  59283. }
  59284. }
  59285. // particle loop
  59286. index = this.particles[start]._pos;
  59287. var vpos = (index / 3) | 0;
  59288. colorIndex = vpos * 4;
  59289. uvIndex = vpos * 2;
  59290. for (var p = start; p <= end; p++) {
  59291. this._particle = this.particles[p];
  59292. this._shape = this._particle._model._shape;
  59293. this._shapeUV = this._particle._model._shapeUV;
  59294. // call to custom user function to update the particle properties
  59295. this.updateParticle(this._particle);
  59296. // camera-particle distance for depth sorting
  59297. if (this._depthSort && this._depthSortParticles) {
  59298. var dsp = this.depthSortedParticles[p];
  59299. dsp.ind = this._particle._ind;
  59300. dsp.indicesLength = this._particle._model._indicesLength;
  59301. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59302. }
  59303. // skip the computations for inactive or already invisible particles
  59304. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59305. // increment indexes for the next particle
  59306. pt = this._shape.length;
  59307. index += pt * 3;
  59308. colorIndex += pt * 4;
  59309. uvIndex += pt * 2;
  59310. continue;
  59311. }
  59312. if (this._particle.isVisible) {
  59313. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59314. this._particleHasParent = (this._particle.parentId !== null);
  59315. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59316. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59317. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59318. // particle rotation matrix
  59319. if (this.billboard) {
  59320. this._particle.rotation.x = 0.0;
  59321. this._particle.rotation.y = 0.0;
  59322. }
  59323. if (this._computeParticleRotation || this.billboard) {
  59324. if (this._particle.rotationQuaternion) {
  59325. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59326. }
  59327. else {
  59328. this._yaw = this._particle.rotation.y;
  59329. this._pitch = this._particle.rotation.x;
  59330. this._roll = this._particle.rotation.z;
  59331. this._quaternionRotationYPR();
  59332. }
  59333. this._quaternionToRotationMatrix();
  59334. }
  59335. if (this._particleHasParent) {
  59336. this._parent = this.particles[this._particle.parentId];
  59337. 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];
  59338. 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];
  59339. 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];
  59340. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59341. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59342. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59343. if (this._computeParticleRotation || this.billboard) {
  59344. 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];
  59345. 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];
  59346. 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];
  59347. 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];
  59348. 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];
  59349. 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];
  59350. 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];
  59351. 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];
  59352. 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];
  59353. }
  59354. }
  59355. else {
  59356. this._particle._globalPosition.x = this._particle.position.x;
  59357. this._particle._globalPosition.y = this._particle.position.y;
  59358. this._particle._globalPosition.z = this._particle.position.z;
  59359. if (this._computeParticleRotation || this.billboard) {
  59360. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59361. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59362. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59363. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59364. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59365. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59366. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59367. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59368. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59369. }
  59370. }
  59371. if (this._particle.translateFromPivot) {
  59372. this._pivotBackTranslation.x = 0.0;
  59373. this._pivotBackTranslation.y = 0.0;
  59374. this._pivotBackTranslation.z = 0.0;
  59375. }
  59376. else {
  59377. this._pivotBackTranslation.x = this._scaledPivot.x;
  59378. this._pivotBackTranslation.y = this._scaledPivot.y;
  59379. this._pivotBackTranslation.z = this._scaledPivot.z;
  59380. }
  59381. // particle vertex loop
  59382. for (pt = 0; pt < this._shape.length; pt++) {
  59383. idx = index + pt * 3;
  59384. colidx = colorIndex + pt * 4;
  59385. uvidx = uvIndex + pt * 2;
  59386. this._vertex.x = this._shape[pt].x;
  59387. this._vertex.y = this._shape[pt].y;
  59388. this._vertex.z = this._shape[pt].z;
  59389. if (this._computeParticleVertex) {
  59390. this.updateParticleVertex(this._particle, this._vertex, pt);
  59391. }
  59392. // positions
  59393. this._vertex.x *= this._particle.scaling.x;
  59394. this._vertex.y *= this._particle.scaling.y;
  59395. this._vertex.z *= this._particle.scaling.z;
  59396. this._vertex.x -= this._scaledPivot.x;
  59397. this._vertex.y -= this._scaledPivot.y;
  59398. this._vertex.z -= this._scaledPivot.z;
  59399. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59400. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59401. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59402. this._rotated.x += this._pivotBackTranslation.x;
  59403. this._rotated.y += this._pivotBackTranslation.y;
  59404. this._rotated.z += this._pivotBackTranslation.z;
  59405. 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;
  59406. 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;
  59407. 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;
  59408. if (this._computeBoundingBox) {
  59409. if (this._positions32[idx] < this._minimum.x) {
  59410. this._minimum.x = this._positions32[idx];
  59411. }
  59412. if (this._positions32[idx] > this._maximum.x) {
  59413. this._maximum.x = this._positions32[idx];
  59414. }
  59415. if (this._positions32[idx + 1] < this._minimum.y) {
  59416. this._minimum.y = this._positions32[idx + 1];
  59417. }
  59418. if (this._positions32[idx + 1] > this._maximum.y) {
  59419. this._maximum.y = this._positions32[idx + 1];
  59420. }
  59421. if (this._positions32[idx + 2] < this._minimum.z) {
  59422. this._minimum.z = this._positions32[idx + 2];
  59423. }
  59424. if (this._positions32[idx + 2] > this._maximum.z) {
  59425. this._maximum.z = this._positions32[idx + 2];
  59426. }
  59427. }
  59428. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59429. if (!this._computeParticleVertex) {
  59430. this._normal.x = this._fixedNormal32[idx];
  59431. this._normal.y = this._fixedNormal32[idx + 1];
  59432. this._normal.z = this._fixedNormal32[idx + 2];
  59433. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59434. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59435. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59436. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59437. 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;
  59438. 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;
  59439. }
  59440. if (this._computeParticleColor && this._particle.color) {
  59441. this._colors32[colidx] = this._particle.color.r;
  59442. this._colors32[colidx + 1] = this._particle.color.g;
  59443. this._colors32[colidx + 2] = this._particle.color.b;
  59444. this._colors32[colidx + 3] = this._particle.color.a;
  59445. }
  59446. if (this._computeParticleTexture) {
  59447. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59448. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59449. }
  59450. }
  59451. }
  59452. // particle just set invisible : scaled to zero and positioned at the origin
  59453. else {
  59454. this._particle._stillInvisible = true; // mark the particle as invisible
  59455. for (pt = 0; pt < this._shape.length; pt++) {
  59456. idx = index + pt * 3;
  59457. colidx = colorIndex + pt * 4;
  59458. uvidx = uvIndex + pt * 2;
  59459. this._positions32[idx] = 0.0;
  59460. this._positions32[idx + 1] = 0.0;
  59461. this._positions32[idx + 2] = 0.0;
  59462. this._normals32[idx] = 0.0;
  59463. this._normals32[idx + 1] = 0.0;
  59464. this._normals32[idx + 2] = 0.0;
  59465. if (this._computeParticleColor && this._particle.color) {
  59466. this._colors32[colidx] = this._particle.color.r;
  59467. this._colors32[colidx + 1] = this._particle.color.g;
  59468. this._colors32[colidx + 2] = this._particle.color.b;
  59469. this._colors32[colidx + 3] = this._particle.color.a;
  59470. }
  59471. if (this._computeParticleTexture) {
  59472. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59473. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59474. }
  59475. }
  59476. }
  59477. // if the particle intersections must be computed : update the bbInfo
  59478. if (this._particlesIntersect) {
  59479. var bInfo = this._particle._boundingInfo;
  59480. var bBox = bInfo.boundingBox;
  59481. var bSphere = bInfo.boundingSphere;
  59482. if (!this._bSphereOnly) {
  59483. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59484. for (var b = 0; b < bBox.vectors.length; b++) {
  59485. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59486. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59487. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59488. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59489. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59490. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59491. 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;
  59492. 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;
  59493. 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;
  59494. }
  59495. bBox._update(this.mesh._worldMatrix);
  59496. }
  59497. // place and scale the particle bouding sphere in the SPS local system, then update it
  59498. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59499. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59500. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59501. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59502. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59503. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59504. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59505. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59506. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59507. 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));
  59508. bSphere._update(this.mesh._worldMatrix);
  59509. }
  59510. // increment indexes for the next particle
  59511. index = idx + 3;
  59512. colorIndex = colidx + 4;
  59513. uvIndex = uvidx + 2;
  59514. }
  59515. // if the VBO must be updated
  59516. if (update) {
  59517. if (this._computeParticleColor) {
  59518. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59519. }
  59520. if (this._computeParticleTexture) {
  59521. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59522. }
  59523. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59524. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59525. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59526. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59527. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59528. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59529. for (var i = 0; i < this._normals32.length; i++) {
  59530. this._fixedNormal32[i] = this._normals32[i];
  59531. }
  59532. }
  59533. if (!this.mesh.areNormalsFrozen) {
  59534. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59535. }
  59536. }
  59537. if (this._depthSort && this._depthSortParticles) {
  59538. this.depthSortedParticles.sort(this._depthSortFunction);
  59539. var dspl = this.depthSortedParticles.length;
  59540. var sorted = 0;
  59541. var lind = 0;
  59542. var sind = 0;
  59543. var sid = 0;
  59544. for (sorted = 0; sorted < dspl; sorted++) {
  59545. lind = this.depthSortedParticles[sorted].indicesLength;
  59546. sind = this.depthSortedParticles[sorted].ind;
  59547. for (var i = 0; i < lind; i++) {
  59548. this._indices32[sid] = this._indices[sind + i];
  59549. sid++;
  59550. }
  59551. }
  59552. this.mesh.updateIndices(this._indices32);
  59553. }
  59554. }
  59555. if (this._computeBoundingBox) {
  59556. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59557. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59558. }
  59559. this.afterUpdateParticles(start, end, update);
  59560. return this;
  59561. };
  59562. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59563. this._halfroll = this._roll * 0.5;
  59564. this._halfpitch = this._pitch * 0.5;
  59565. this._halfyaw = this._yaw * 0.5;
  59566. this._sinRoll = Math.sin(this._halfroll);
  59567. this._cosRoll = Math.cos(this._halfroll);
  59568. this._sinPitch = Math.sin(this._halfpitch);
  59569. this._cosPitch = Math.cos(this._halfpitch);
  59570. this._sinYaw = Math.sin(this._halfyaw);
  59571. this._cosYaw = Math.cos(this._halfyaw);
  59572. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59573. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59574. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59575. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59576. };
  59577. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59578. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59579. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59580. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59581. this._rotMatrix.m[3] = 0;
  59582. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59583. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59584. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59585. this._rotMatrix.m[7] = 0;
  59586. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59587. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59588. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59589. this._rotMatrix.m[11] = 0;
  59590. this._rotMatrix.m[12] = 0;
  59591. this._rotMatrix.m[13] = 0;
  59592. this._rotMatrix.m[14] = 0;
  59593. this._rotMatrix.m[15] = 1.0;
  59594. };
  59595. /**
  59596. * Disposes the SPS.
  59597. */
  59598. SolidParticleSystem.prototype.dispose = function () {
  59599. this.mesh.dispose();
  59600. this.vars = null;
  59601. // drop references to internal big arrays for the GC
  59602. this._positions = null;
  59603. this._indices = null;
  59604. this._normals = null;
  59605. this._uvs = null;
  59606. this._colors = null;
  59607. this._indices32 = null;
  59608. this._positions32 = null;
  59609. this._normals32 = null;
  59610. this._fixedNormal32 = null;
  59611. this._uvs32 = null;
  59612. this._colors32 = null;
  59613. this.pickedParticles = null;
  59614. };
  59615. /**
  59616. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59617. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59618. * @returns the SPS.
  59619. */
  59620. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59621. if (!this._isVisibilityBoxLocked) {
  59622. this.mesh.refreshBoundingInfo();
  59623. }
  59624. return this;
  59625. };
  59626. /**
  59627. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59628. * @param size the size (float) of the visibility box
  59629. * note : this doesn't lock the SPS mesh bounding box.
  59630. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59631. */
  59632. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59633. var vis = size / 2;
  59634. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59635. };
  59636. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59637. /**
  59638. * Gets whether the SPS as always visible or not
  59639. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59640. */
  59641. get: function () {
  59642. return this._alwaysVisible;
  59643. },
  59644. /**
  59645. * Sets the SPS as always visible or not
  59646. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59647. */
  59648. set: function (val) {
  59649. this._alwaysVisible = val;
  59650. this.mesh.alwaysSelectAsActiveMesh = val;
  59651. },
  59652. enumerable: true,
  59653. configurable: true
  59654. });
  59655. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59656. /**
  59657. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59658. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59659. */
  59660. get: function () {
  59661. return this._isVisibilityBoxLocked;
  59662. },
  59663. /**
  59664. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59665. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59666. */
  59667. set: function (val) {
  59668. this._isVisibilityBoxLocked = val;
  59669. var boundingInfo = this.mesh.getBoundingInfo();
  59670. boundingInfo.isLocked = val;
  59671. },
  59672. enumerable: true,
  59673. configurable: true
  59674. });
  59675. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59676. /**
  59677. * Gets if `setParticles()` computes the particle rotations or not.
  59678. * Default value : true. The SPS is faster when it's set to false.
  59679. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59680. */
  59681. get: function () {
  59682. return this._computeParticleRotation;
  59683. },
  59684. /**
  59685. * Tells to `setParticles()` to compute the particle rotations or not.
  59686. * Default value : true. The SPS is faster when it's set to false.
  59687. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59688. */
  59689. set: function (val) {
  59690. this._computeParticleRotation = val;
  59691. },
  59692. enumerable: true,
  59693. configurable: true
  59694. });
  59695. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59696. /**
  59697. * Gets if `setParticles()` computes the particle colors or not.
  59698. * Default value : true. The SPS is faster when it's set to false.
  59699. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59700. */
  59701. get: function () {
  59702. return this._computeParticleColor;
  59703. },
  59704. /**
  59705. * Tells to `setParticles()` to compute the particle colors or not.
  59706. * Default value : true. The SPS is faster when it's set to false.
  59707. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59708. */
  59709. set: function (val) {
  59710. this._computeParticleColor = val;
  59711. },
  59712. enumerable: true,
  59713. configurable: true
  59714. });
  59715. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59716. /**
  59717. * Gets if `setParticles()` computes the particle textures or not.
  59718. * Default value : true. The SPS is faster when it's set to false.
  59719. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59720. */
  59721. get: function () {
  59722. return this._computeParticleTexture;
  59723. },
  59724. set: function (val) {
  59725. this._computeParticleTexture = val;
  59726. },
  59727. enumerable: true,
  59728. configurable: true
  59729. });
  59730. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59731. /**
  59732. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59733. * Default value : false. The SPS is faster when it's set to false.
  59734. * Note : the particle custom vertex positions aren't stored values.
  59735. */
  59736. get: function () {
  59737. return this._computeParticleVertex;
  59738. },
  59739. /**
  59740. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59741. * Default value : false. The SPS is faster when it's set to false.
  59742. * Note : the particle custom vertex positions aren't stored values.
  59743. */
  59744. set: function (val) {
  59745. this._computeParticleVertex = val;
  59746. },
  59747. enumerable: true,
  59748. configurable: true
  59749. });
  59750. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59751. /**
  59752. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59753. */
  59754. get: function () {
  59755. return this._computeBoundingBox;
  59756. },
  59757. /**
  59758. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59759. */
  59760. set: function (val) {
  59761. this._computeBoundingBox = val;
  59762. },
  59763. enumerable: true,
  59764. configurable: true
  59765. });
  59766. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59767. /**
  59768. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59769. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59770. * Default : `true`
  59771. */
  59772. get: function () {
  59773. return this._depthSortParticles;
  59774. },
  59775. /**
  59776. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59777. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59778. * Default : `true`
  59779. */
  59780. set: function (val) {
  59781. this._depthSortParticles = val;
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. // =======================================================================
  59787. // Particle behavior logic
  59788. // these following methods may be overwritten by the user to fit his needs
  59789. /**
  59790. * This function does nothing. It may be overwritten to set all the particle first values.
  59791. * The SPS doesn't call this function, you may have to call it by your own.
  59792. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59793. */
  59794. SolidParticleSystem.prototype.initParticles = function () {
  59795. };
  59796. /**
  59797. * This function does nothing. It may be overwritten to recycle a particle.
  59798. * The SPS doesn't call this function, you may have to call it by your own.
  59799. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59800. * @param particle The particle to recycle
  59801. * @returns the recycled particle
  59802. */
  59803. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59804. return particle;
  59805. };
  59806. /**
  59807. * Updates a particle : this function should be overwritten by the user.
  59808. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59809. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59810. * @example : just set a particle position or velocity and recycle conditions
  59811. * @param particle The particle to update
  59812. * @returns the updated particle
  59813. */
  59814. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59815. return particle;
  59816. };
  59817. /**
  59818. * Updates a vertex of a particle : it can be overwritten by the user.
  59819. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59820. * @param particle the current particle
  59821. * @param vertex the current index of the current particle
  59822. * @param pt the index of the current vertex in the particle shape
  59823. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59824. * @example : just set a vertex particle position
  59825. * @returns the updated vertex
  59826. */
  59827. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59828. return vertex;
  59829. };
  59830. /**
  59831. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59832. * This does nothing and may be overwritten by the user.
  59833. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59834. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59835. * @param update the boolean update value actually passed to setParticles()
  59836. */
  59837. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59838. };
  59839. /**
  59840. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59841. * This will be passed three parameters.
  59842. * This does nothing and may be overwritten by the user.
  59843. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59844. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59845. * @param update the boolean update value actually passed to setParticles()
  59846. */
  59847. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59848. };
  59849. return SolidParticleSystem;
  59850. }());
  59851. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59852. })(BABYLON || (BABYLON = {}));
  59853. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59854. var BABYLON;
  59855. (function (BABYLON) {
  59856. var ShaderMaterial = /** @class */ (function (_super) {
  59857. __extends(ShaderMaterial, _super);
  59858. function ShaderMaterial(name, scene, shaderPath, options) {
  59859. var _this = _super.call(this, name, scene) || this;
  59860. _this._textures = {};
  59861. _this._textureArrays = {};
  59862. _this._floats = {};
  59863. _this._ints = {};
  59864. _this._floatsArrays = {};
  59865. _this._colors3 = {};
  59866. _this._colors3Arrays = {};
  59867. _this._colors4 = {};
  59868. _this._vectors2 = {};
  59869. _this._vectors3 = {};
  59870. _this._vectors4 = {};
  59871. _this._matrices = {};
  59872. _this._matrices3x3 = {};
  59873. _this._matrices2x2 = {};
  59874. _this._vectors2Arrays = {};
  59875. _this._vectors3Arrays = {};
  59876. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59877. _this._shaderPath = shaderPath;
  59878. options.needAlphaBlending = options.needAlphaBlending || false;
  59879. options.needAlphaTesting = options.needAlphaTesting || false;
  59880. options.attributes = options.attributes || ["position", "normal", "uv"];
  59881. options.uniforms = options.uniforms || ["worldViewProjection"];
  59882. options.uniformBuffers = options.uniformBuffers || [];
  59883. options.samplers = options.samplers || [];
  59884. options.defines = options.defines || [];
  59885. _this._options = options;
  59886. return _this;
  59887. }
  59888. ShaderMaterial.prototype.getClassName = function () {
  59889. return "ShaderMaterial";
  59890. };
  59891. ShaderMaterial.prototype.needAlphaBlending = function () {
  59892. return this._options.needAlphaBlending;
  59893. };
  59894. ShaderMaterial.prototype.needAlphaTesting = function () {
  59895. return this._options.needAlphaTesting;
  59896. };
  59897. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59898. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59899. this._options.uniforms.push(uniformName);
  59900. }
  59901. };
  59902. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59903. if (this._options.samplers.indexOf(name) === -1) {
  59904. this._options.samplers.push(name);
  59905. }
  59906. this._textures[name] = texture;
  59907. return this;
  59908. };
  59909. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59910. if (this._options.samplers.indexOf(name) === -1) {
  59911. this._options.samplers.push(name);
  59912. }
  59913. this._checkUniform(name);
  59914. this._textureArrays[name] = textures;
  59915. return this;
  59916. };
  59917. ShaderMaterial.prototype.setFloat = function (name, value) {
  59918. this._checkUniform(name);
  59919. this._floats[name] = value;
  59920. return this;
  59921. };
  59922. ShaderMaterial.prototype.setInt = function (name, value) {
  59923. this._checkUniform(name);
  59924. this._ints[name] = value;
  59925. return this;
  59926. };
  59927. ShaderMaterial.prototype.setFloats = function (name, value) {
  59928. this._checkUniform(name);
  59929. this._floatsArrays[name] = value;
  59930. return this;
  59931. };
  59932. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59933. this._checkUniform(name);
  59934. this._colors3[name] = value;
  59935. return this;
  59936. };
  59937. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59938. this._checkUniform(name);
  59939. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59940. color.toArray(arr, arr.length);
  59941. return arr;
  59942. }, []);
  59943. return this;
  59944. };
  59945. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59946. this._checkUniform(name);
  59947. this._colors4[name] = value;
  59948. return this;
  59949. };
  59950. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59951. this._checkUniform(name);
  59952. this._vectors2[name] = value;
  59953. return this;
  59954. };
  59955. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59956. this._checkUniform(name);
  59957. this._vectors3[name] = value;
  59958. return this;
  59959. };
  59960. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59961. this._checkUniform(name);
  59962. this._vectors4[name] = value;
  59963. return this;
  59964. };
  59965. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59966. this._checkUniform(name);
  59967. this._matrices[name] = value;
  59968. return this;
  59969. };
  59970. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59971. this._checkUniform(name);
  59972. this._matrices3x3[name] = value;
  59973. return this;
  59974. };
  59975. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59976. this._checkUniform(name);
  59977. this._matrices2x2[name] = value;
  59978. return this;
  59979. };
  59980. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59981. this._checkUniform(name);
  59982. this._vectors2Arrays[name] = value;
  59983. return this;
  59984. };
  59985. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59986. this._checkUniform(name);
  59987. this._vectors3Arrays[name] = value;
  59988. return this;
  59989. };
  59990. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59991. if (!mesh) {
  59992. return true;
  59993. }
  59994. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59995. return false;
  59996. }
  59997. return false;
  59998. };
  59999. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60000. var scene = this.getScene();
  60001. var engine = scene.getEngine();
  60002. if (!this.checkReadyOnEveryCall) {
  60003. if (this._renderId === scene.getRenderId()) {
  60004. if (this._checkCache(scene, mesh, useInstances)) {
  60005. return true;
  60006. }
  60007. }
  60008. }
  60009. // Instances
  60010. var defines = [];
  60011. var attribs = [];
  60012. var fallbacks = new BABYLON.EffectFallbacks();
  60013. if (useInstances) {
  60014. defines.push("#define INSTANCES");
  60015. }
  60016. for (var index = 0; index < this._options.defines.length; index++) {
  60017. defines.push(this._options.defines[index]);
  60018. }
  60019. for (var index = 0; index < this._options.attributes.length; index++) {
  60020. attribs.push(this._options.attributes[index]);
  60021. }
  60022. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60023. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60024. defines.push("#define VERTEXCOLOR");
  60025. }
  60026. // Bones
  60027. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60030. if (mesh.numBoneInfluencers > 4) {
  60031. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60032. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60033. }
  60034. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60035. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60036. fallbacks.addCPUSkinningFallback(0, mesh);
  60037. if (this._options.uniforms.indexOf("mBones") === -1) {
  60038. this._options.uniforms.push("mBones");
  60039. }
  60040. }
  60041. else {
  60042. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60043. }
  60044. // Textures
  60045. for (var name in this._textures) {
  60046. if (!this._textures[name].isReady()) {
  60047. return false;
  60048. }
  60049. }
  60050. // Alpha test
  60051. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60052. defines.push("#define ALPHATEST");
  60053. }
  60054. var previousEffect = this._effect;
  60055. var join = defines.join("\n");
  60056. this._effect = engine.createEffect(this._shaderPath, {
  60057. attributes: attribs,
  60058. uniformsNames: this._options.uniforms,
  60059. uniformBuffersNames: this._options.uniformBuffers,
  60060. samplers: this._options.samplers,
  60061. defines: join,
  60062. fallbacks: fallbacks,
  60063. onCompiled: this.onCompiled,
  60064. onError: this.onError
  60065. }, engine);
  60066. if (!this._effect.isReady()) {
  60067. return false;
  60068. }
  60069. if (previousEffect !== this._effect) {
  60070. scene.resetCachedMaterial();
  60071. }
  60072. this._renderId = scene.getRenderId();
  60073. return true;
  60074. };
  60075. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60076. var scene = this.getScene();
  60077. if (!this._effect) {
  60078. return;
  60079. }
  60080. if (this._options.uniforms.indexOf("world") !== -1) {
  60081. this._effect.setMatrix("world", world);
  60082. }
  60083. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60084. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60085. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60086. }
  60087. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60088. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60089. }
  60090. };
  60091. ShaderMaterial.prototype.bind = function (world, mesh) {
  60092. // Std values
  60093. this.bindOnlyWorldMatrix(world);
  60094. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60095. if (this._options.uniforms.indexOf("view") !== -1) {
  60096. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60097. }
  60098. if (this._options.uniforms.indexOf("projection") !== -1) {
  60099. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60100. }
  60101. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60102. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60103. }
  60104. // Bones
  60105. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60106. var name;
  60107. // Texture
  60108. for (name in this._textures) {
  60109. this._effect.setTexture(name, this._textures[name]);
  60110. }
  60111. // Texture arrays
  60112. for (name in this._textureArrays) {
  60113. this._effect.setTextureArray(name, this._textureArrays[name]);
  60114. }
  60115. // Int
  60116. for (name in this._ints) {
  60117. this._effect.setInt(name, this._ints[name]);
  60118. }
  60119. // Float
  60120. for (name in this._floats) {
  60121. this._effect.setFloat(name, this._floats[name]);
  60122. }
  60123. // Floats
  60124. for (name in this._floatsArrays) {
  60125. this._effect.setArray(name, this._floatsArrays[name]);
  60126. }
  60127. // Color3
  60128. for (name in this._colors3) {
  60129. this._effect.setColor3(name, this._colors3[name]);
  60130. }
  60131. for (name in this._colors3Arrays) {
  60132. this._effect.setArray3(name, this._colors3Arrays[name]);
  60133. }
  60134. // Color4
  60135. for (name in this._colors4) {
  60136. var color = this._colors4[name];
  60137. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60138. }
  60139. // Vector2
  60140. for (name in this._vectors2) {
  60141. this._effect.setVector2(name, this._vectors2[name]);
  60142. }
  60143. // Vector3
  60144. for (name in this._vectors3) {
  60145. this._effect.setVector3(name, this._vectors3[name]);
  60146. }
  60147. // Vector4
  60148. for (name in this._vectors4) {
  60149. this._effect.setVector4(name, this._vectors4[name]);
  60150. }
  60151. // Matrix
  60152. for (name in this._matrices) {
  60153. this._effect.setMatrix(name, this._matrices[name]);
  60154. }
  60155. // Matrix 3x3
  60156. for (name in this._matrices3x3) {
  60157. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60158. }
  60159. // Matrix 2x2
  60160. for (name in this._matrices2x2) {
  60161. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60162. }
  60163. // Vector2Array
  60164. for (name in this._vectors2Arrays) {
  60165. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60166. }
  60167. // Vector3Array
  60168. for (name in this._vectors3Arrays) {
  60169. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60170. }
  60171. }
  60172. this._afterBind(mesh);
  60173. };
  60174. ShaderMaterial.prototype.getActiveTextures = function () {
  60175. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60176. for (var name in this._textures) {
  60177. activeTextures.push(this._textures[name]);
  60178. }
  60179. for (var name in this._textureArrays) {
  60180. var array = this._textureArrays[name];
  60181. for (var index = 0; index < array.length; index++) {
  60182. activeTextures.push(array[index]);
  60183. }
  60184. }
  60185. return activeTextures;
  60186. };
  60187. ShaderMaterial.prototype.hasTexture = function (texture) {
  60188. if (_super.prototype.hasTexture.call(this, texture)) {
  60189. return true;
  60190. }
  60191. for (var name in this._textures) {
  60192. if (this._textures[name] === texture) {
  60193. return true;
  60194. }
  60195. }
  60196. for (var name in this._textureArrays) {
  60197. var array = this._textureArrays[name];
  60198. for (var index = 0; index < array.length; index++) {
  60199. if (array[index] === texture) {
  60200. return true;
  60201. }
  60202. }
  60203. }
  60204. return false;
  60205. };
  60206. ShaderMaterial.prototype.clone = function (name) {
  60207. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60208. return newShaderMaterial;
  60209. };
  60210. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60211. if (forceDisposeTextures) {
  60212. var name;
  60213. for (name in this._textures) {
  60214. this._textures[name].dispose();
  60215. }
  60216. for (name in this._textureArrays) {
  60217. var array = this._textureArrays[name];
  60218. for (var index = 0; index < array.length; index++) {
  60219. array[index].dispose();
  60220. }
  60221. }
  60222. }
  60223. this._textures = {};
  60224. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60225. };
  60226. ShaderMaterial.prototype.serialize = function () {
  60227. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60228. serializationObject.customType = "BABYLON.ShaderMaterial";
  60229. serializationObject.options = this._options;
  60230. serializationObject.shaderPath = this._shaderPath;
  60231. var name;
  60232. // Texture
  60233. serializationObject.textures = {};
  60234. for (name in this._textures) {
  60235. serializationObject.textures[name] = this._textures[name].serialize();
  60236. }
  60237. // Texture arrays
  60238. serializationObject.textureArrays = {};
  60239. for (name in this._textureArrays) {
  60240. serializationObject.textureArrays[name] = [];
  60241. var array = this._textureArrays[name];
  60242. for (var index = 0; index < array.length; index++) {
  60243. serializationObject.textureArrays[name].push(array[index].serialize());
  60244. }
  60245. }
  60246. // Float
  60247. serializationObject.floats = {};
  60248. for (name in this._floats) {
  60249. serializationObject.floats[name] = this._floats[name];
  60250. }
  60251. // Float s
  60252. serializationObject.FloatArrays = {};
  60253. for (name in this._floatsArrays) {
  60254. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60255. }
  60256. // Color3
  60257. serializationObject.colors3 = {};
  60258. for (name in this._colors3) {
  60259. serializationObject.colors3[name] = this._colors3[name].asArray();
  60260. }
  60261. // Color3 array
  60262. serializationObject.colors3Arrays = {};
  60263. for (name in this._colors3Arrays) {
  60264. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60265. }
  60266. // Color4
  60267. serializationObject.colors4 = {};
  60268. for (name in this._colors4) {
  60269. serializationObject.colors4[name] = this._colors4[name].asArray();
  60270. }
  60271. // Vector2
  60272. serializationObject.vectors2 = {};
  60273. for (name in this._vectors2) {
  60274. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60275. }
  60276. // Vector3
  60277. serializationObject.vectors3 = {};
  60278. for (name in this._vectors3) {
  60279. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60280. }
  60281. // Vector4
  60282. serializationObject.vectors4 = {};
  60283. for (name in this._vectors4) {
  60284. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60285. }
  60286. // Matrix
  60287. serializationObject.matrices = {};
  60288. for (name in this._matrices) {
  60289. serializationObject.matrices[name] = this._matrices[name].asArray();
  60290. }
  60291. // Matrix 3x3
  60292. serializationObject.matrices3x3 = {};
  60293. for (name in this._matrices3x3) {
  60294. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60295. }
  60296. // Matrix 2x2
  60297. serializationObject.matrices2x2 = {};
  60298. for (name in this._matrices2x2) {
  60299. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60300. }
  60301. // Vector2Array
  60302. serializationObject.vectors2Arrays = {};
  60303. for (name in this._vectors2Arrays) {
  60304. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60305. }
  60306. // Vector3Array
  60307. serializationObject.vectors3Arrays = {};
  60308. for (name in this._vectors3Arrays) {
  60309. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60310. }
  60311. return serializationObject;
  60312. };
  60313. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60314. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60315. var name;
  60316. // Texture
  60317. for (name in source.textures) {
  60318. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60319. }
  60320. // Texture arrays
  60321. for (name in source.textureArrays) {
  60322. var array = source.textureArrays[name];
  60323. var textureArray = new Array();
  60324. for (var index = 0; index < array.length; index++) {
  60325. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60326. }
  60327. material.setTextureArray(name, textureArray);
  60328. }
  60329. // Float
  60330. for (name in source.floats) {
  60331. material.setFloat(name, source.floats[name]);
  60332. }
  60333. // Float s
  60334. for (name in source.floatsArrays) {
  60335. material.setFloats(name, source.floatsArrays[name]);
  60336. }
  60337. // Color3
  60338. for (name in source.colors3) {
  60339. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60340. }
  60341. // Color3 arrays
  60342. for (name in source.colors3Arrays) {
  60343. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60344. if (i % 3 === 0) {
  60345. arr.push([num]);
  60346. }
  60347. else {
  60348. arr[arr.length - 1].push(num);
  60349. }
  60350. return arr;
  60351. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60352. material.setColor3Array(name, colors);
  60353. }
  60354. // Color4
  60355. for (name in source.colors4) {
  60356. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60357. }
  60358. // Vector2
  60359. for (name in source.vectors2) {
  60360. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60361. }
  60362. // Vector3
  60363. for (name in source.vectors3) {
  60364. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60365. }
  60366. // Vector4
  60367. for (name in source.vectors4) {
  60368. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60369. }
  60370. // Matrix
  60371. for (name in source.matrices) {
  60372. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60373. }
  60374. // Matrix 3x3
  60375. for (name in source.matrices3x3) {
  60376. material.setMatrix3x3(name, source.matrices3x3[name]);
  60377. }
  60378. // Matrix 2x2
  60379. for (name in source.matrices2x2) {
  60380. material.setMatrix2x2(name, source.matrices2x2[name]);
  60381. }
  60382. // Vector2Array
  60383. for (name in source.vectors2Arrays) {
  60384. material.setArray2(name, source.vectors2Arrays[name]);
  60385. }
  60386. // Vector3Array
  60387. for (name in source.vectors3Arrays) {
  60388. material.setArray3(name, source.vectors3Arrays[name]);
  60389. }
  60390. return material;
  60391. };
  60392. return ShaderMaterial;
  60393. }(BABYLON.Material));
  60394. BABYLON.ShaderMaterial = ShaderMaterial;
  60395. })(BABYLON || (BABYLON = {}));
  60396. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60397. var BABYLON;
  60398. (function (BABYLON) {
  60399. var GroundMesh = /** @class */ (function (_super) {
  60400. __extends(GroundMesh, _super);
  60401. function GroundMesh(name, scene) {
  60402. var _this = _super.call(this, name, scene) || this;
  60403. _this.generateOctree = false;
  60404. return _this;
  60405. }
  60406. GroundMesh.prototype.getClassName = function () {
  60407. return "GroundMesh";
  60408. };
  60409. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60410. get: function () {
  60411. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60412. },
  60413. enumerable: true,
  60414. configurable: true
  60415. });
  60416. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60417. get: function () {
  60418. return this._subdivisionsX;
  60419. },
  60420. enumerable: true,
  60421. configurable: true
  60422. });
  60423. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60424. get: function () {
  60425. return this._subdivisionsY;
  60426. },
  60427. enumerable: true,
  60428. configurable: true
  60429. });
  60430. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60431. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60432. this._subdivisionsX = chunksCount;
  60433. this._subdivisionsY = chunksCount;
  60434. this.subdivide(chunksCount);
  60435. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60436. };
  60437. /**
  60438. * Returns a height (y) value in the Worl system :
  60439. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60440. * Returns the ground y position if (x, z) are outside the ground surface.
  60441. */
  60442. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60443. var world = this.getWorldMatrix();
  60444. var invMat = BABYLON.Tmp.Matrix[5];
  60445. world.invertToRef(invMat);
  60446. var tmpVect = BABYLON.Tmp.Vector3[8];
  60447. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60448. x = tmpVect.x;
  60449. z = tmpVect.z;
  60450. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60451. return this.position.y;
  60452. }
  60453. if (!this._heightQuads || this._heightQuads.length == 0) {
  60454. this._initHeightQuads();
  60455. this._computeHeightQuads();
  60456. }
  60457. var facet = this._getFacetAt(x, z);
  60458. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60459. // return y in the World system
  60460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60461. return tmpVect.y;
  60462. };
  60463. /**
  60464. * Returns a normalized vector (Vector3) orthogonal to the ground
  60465. * at the ground coordinates (x, z) expressed in the World system.
  60466. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60467. */
  60468. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60469. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60470. this.getNormalAtCoordinatesToRef(x, z, normal);
  60471. return normal;
  60472. };
  60473. /**
  60474. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60475. * at the ground coordinates (x, z) expressed in the World system.
  60476. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60477. * Returns the GroundMesh.
  60478. */
  60479. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60480. var world = this.getWorldMatrix();
  60481. var tmpMat = BABYLON.Tmp.Matrix[5];
  60482. world.invertToRef(tmpMat);
  60483. var tmpVect = BABYLON.Tmp.Vector3[8];
  60484. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60485. x = tmpVect.x;
  60486. z = tmpVect.z;
  60487. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60488. return this;
  60489. }
  60490. if (!this._heightQuads || this._heightQuads.length == 0) {
  60491. this._initHeightQuads();
  60492. this._computeHeightQuads();
  60493. }
  60494. var facet = this._getFacetAt(x, z);
  60495. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60496. return this;
  60497. };
  60498. /**
  60499. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60500. * if the ground has been updated.
  60501. * This can be used in the render loop.
  60502. * Returns the GroundMesh.
  60503. */
  60504. GroundMesh.prototype.updateCoordinateHeights = function () {
  60505. if (!this._heightQuads || this._heightQuads.length == 0) {
  60506. this._initHeightQuads();
  60507. }
  60508. this._computeHeightQuads();
  60509. return this;
  60510. };
  60511. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60512. GroundMesh.prototype._getFacetAt = function (x, z) {
  60513. // retrieve col and row from x, z coordinates in the ground local system
  60514. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60515. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60516. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60517. var facet;
  60518. if (z < quad.slope.x * x + quad.slope.y) {
  60519. facet = quad.facet1;
  60520. }
  60521. else {
  60522. facet = quad.facet2;
  60523. }
  60524. return facet;
  60525. };
  60526. // Creates and populates the heightMap array with "facet" elements :
  60527. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60528. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60529. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60530. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60531. // Returns the GroundMesh.
  60532. GroundMesh.prototype._initHeightQuads = function () {
  60533. var subdivisionsX = this._subdivisionsX;
  60534. var subdivisionsY = this._subdivisionsY;
  60535. this._heightQuads = new Array();
  60536. for (var row = 0; row < subdivisionsY; row++) {
  60537. for (var col = 0; col < subdivisionsX; col++) {
  60538. 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) };
  60539. this._heightQuads[row * subdivisionsX + col] = quad;
  60540. }
  60541. }
  60542. return this;
  60543. };
  60544. // Compute each quad element values and update the the heightMap array :
  60545. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60546. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60547. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60548. // Returns the GroundMesh.
  60549. GroundMesh.prototype._computeHeightQuads = function () {
  60550. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60551. if (!positions) {
  60552. return this;
  60553. }
  60554. var v1 = BABYLON.Tmp.Vector3[3];
  60555. var v2 = BABYLON.Tmp.Vector3[2];
  60556. var v3 = BABYLON.Tmp.Vector3[1];
  60557. var v4 = BABYLON.Tmp.Vector3[0];
  60558. var v1v2 = BABYLON.Tmp.Vector3[4];
  60559. var v1v3 = BABYLON.Tmp.Vector3[5];
  60560. var v1v4 = BABYLON.Tmp.Vector3[6];
  60561. var norm1 = BABYLON.Tmp.Vector3[7];
  60562. var norm2 = BABYLON.Tmp.Vector3[8];
  60563. var i = 0;
  60564. var j = 0;
  60565. var k = 0;
  60566. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60567. var h = 0;
  60568. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60569. var d2 = 0;
  60570. var subdivisionsX = this._subdivisionsX;
  60571. var subdivisionsY = this._subdivisionsY;
  60572. for (var row = 0; row < subdivisionsY; row++) {
  60573. for (var col = 0; col < subdivisionsX; col++) {
  60574. i = col * 3;
  60575. j = row * (subdivisionsX + 1) * 3;
  60576. k = (row + 1) * (subdivisionsX + 1) * 3;
  60577. v1.x = positions[j + i];
  60578. v1.y = positions[j + i + 1];
  60579. v1.z = positions[j + i + 2];
  60580. v2.x = positions[j + i + 3];
  60581. v2.y = positions[j + i + 4];
  60582. v2.z = positions[j + i + 5];
  60583. v3.x = positions[k + i];
  60584. v3.y = positions[k + i + 1];
  60585. v3.z = positions[k + i + 2];
  60586. v4.x = positions[k + i + 3];
  60587. v4.y = positions[k + i + 4];
  60588. v4.z = positions[k + i + 5];
  60589. // 2D slope V1V4
  60590. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60591. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60592. // facet equations :
  60593. // we compute each facet normal vector
  60594. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60595. // we compute the value d by applying the equation to v1 which belongs to the plane
  60596. // then we store the facet equation in a Vector4
  60597. v2.subtractToRef(v1, v1v2);
  60598. v3.subtractToRef(v1, v1v3);
  60599. v4.subtractToRef(v1, v1v4);
  60600. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60601. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60602. norm1.normalize();
  60603. norm2.normalize();
  60604. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60605. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60606. var quad = this._heightQuads[row * subdivisionsX + col];
  60607. quad.slope.copyFromFloats(cd, h);
  60608. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60609. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60610. }
  60611. }
  60612. return this;
  60613. };
  60614. GroundMesh.prototype.serialize = function (serializationObject) {
  60615. _super.prototype.serialize.call(this, serializationObject);
  60616. serializationObject.subdivisionsX = this._subdivisionsX;
  60617. serializationObject.subdivisionsY = this._subdivisionsY;
  60618. serializationObject.minX = this._minX;
  60619. serializationObject.maxX = this._maxX;
  60620. serializationObject.minZ = this._minZ;
  60621. serializationObject.maxZ = this._maxZ;
  60622. serializationObject.width = this._width;
  60623. serializationObject.height = this._height;
  60624. };
  60625. GroundMesh.Parse = function (parsedMesh, scene) {
  60626. var result = new GroundMesh(parsedMesh.name, scene);
  60627. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60628. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60629. result._minX = parsedMesh.minX;
  60630. result._maxX = parsedMesh.maxX;
  60631. result._minZ = parsedMesh.minZ;
  60632. result._maxZ = parsedMesh.maxZ;
  60633. result._width = parsedMesh.width;
  60634. result._height = parsedMesh.height;
  60635. return result;
  60636. };
  60637. return GroundMesh;
  60638. }(BABYLON.Mesh));
  60639. BABYLON.GroundMesh = GroundMesh;
  60640. })(BABYLON || (BABYLON = {}));
  60641. //# sourceMappingURL=babylon.groundMesh.js.map
  60642. var BABYLON;
  60643. (function (BABYLON) {
  60644. /**
  60645. * Creates an instance based on a source mesh.
  60646. */
  60647. var InstancedMesh = /** @class */ (function (_super) {
  60648. __extends(InstancedMesh, _super);
  60649. function InstancedMesh(name, source) {
  60650. var _this = _super.call(this, name, source.getScene()) || this;
  60651. source.instances.push(_this);
  60652. _this._sourceMesh = source;
  60653. _this.position.copyFrom(source.position);
  60654. _this.rotation.copyFrom(source.rotation);
  60655. _this.scaling.copyFrom(source.scaling);
  60656. if (source.rotationQuaternion) {
  60657. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60658. }
  60659. _this.infiniteDistance = source.infiniteDistance;
  60660. _this.setPivotMatrix(source.getPivotMatrix());
  60661. _this.refreshBoundingInfo();
  60662. _this._syncSubMeshes();
  60663. return _this;
  60664. }
  60665. /**
  60666. * Returns the string "InstancedMesh".
  60667. */
  60668. InstancedMesh.prototype.getClassName = function () {
  60669. return "InstancedMesh";
  60670. };
  60671. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60672. // Methods
  60673. get: function () {
  60674. return this._sourceMesh.receiveShadows;
  60675. },
  60676. enumerable: true,
  60677. configurable: true
  60678. });
  60679. Object.defineProperty(InstancedMesh.prototype, "material", {
  60680. get: function () {
  60681. return this._sourceMesh.material;
  60682. },
  60683. enumerable: true,
  60684. configurable: true
  60685. });
  60686. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60687. get: function () {
  60688. return this._sourceMesh.visibility;
  60689. },
  60690. enumerable: true,
  60691. configurable: true
  60692. });
  60693. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60694. get: function () {
  60695. return this._sourceMesh.skeleton;
  60696. },
  60697. enumerable: true,
  60698. configurable: true
  60699. });
  60700. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60701. get: function () {
  60702. return this._sourceMesh.renderingGroupId;
  60703. },
  60704. set: function (value) {
  60705. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60706. return;
  60707. }
  60708. //no-op with warning
  60709. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60710. },
  60711. enumerable: true,
  60712. configurable: true
  60713. });
  60714. /**
  60715. * Returns the total number of vertices (integer).
  60716. */
  60717. InstancedMesh.prototype.getTotalVertices = function () {
  60718. return this._sourceMesh.getTotalVertices();
  60719. };
  60720. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60721. get: function () {
  60722. return this._sourceMesh;
  60723. },
  60724. enumerable: true,
  60725. configurable: true
  60726. });
  60727. /**
  60728. * Is this node ready to be used/rendered
  60729. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60730. * @return {boolean} is it ready
  60731. */
  60732. InstancedMesh.prototype.isReady = function (completeCheck) {
  60733. if (completeCheck === void 0) { completeCheck = false; }
  60734. return this._sourceMesh.isReady(completeCheck, true);
  60735. };
  60736. /**
  60737. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60738. */
  60739. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60740. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60741. };
  60742. /**
  60743. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60744. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60745. * The `data` are either a numeric array either a Float32Array.
  60746. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60747. * 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).
  60748. * Note that a new underlying VertexBuffer object is created each call.
  60749. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60750. *
  60751. * Possible `kind` values :
  60752. * - BABYLON.VertexBuffer.PositionKind
  60753. * - BABYLON.VertexBuffer.UVKind
  60754. * - BABYLON.VertexBuffer.UV2Kind
  60755. * - BABYLON.VertexBuffer.UV3Kind
  60756. * - BABYLON.VertexBuffer.UV4Kind
  60757. * - BABYLON.VertexBuffer.UV5Kind
  60758. * - BABYLON.VertexBuffer.UV6Kind
  60759. * - BABYLON.VertexBuffer.ColorKind
  60760. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60761. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60762. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60763. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60764. *
  60765. * Returns the Mesh.
  60766. */
  60767. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60768. if (this.sourceMesh) {
  60769. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60770. }
  60771. return this.sourceMesh;
  60772. };
  60773. /**
  60774. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60775. * If the mesh has no geometry, it is simply returned as it is.
  60776. * The `data` are either a numeric array either a Float32Array.
  60777. * No new underlying VertexBuffer object is created.
  60778. * 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.
  60779. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60780. *
  60781. * Possible `kind` values :
  60782. * - BABYLON.VertexBuffer.PositionKind
  60783. * - BABYLON.VertexBuffer.UVKind
  60784. * - BABYLON.VertexBuffer.UV2Kind
  60785. * - BABYLON.VertexBuffer.UV3Kind
  60786. * - BABYLON.VertexBuffer.UV4Kind
  60787. * - BABYLON.VertexBuffer.UV5Kind
  60788. * - BABYLON.VertexBuffer.UV6Kind
  60789. * - BABYLON.VertexBuffer.ColorKind
  60790. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60791. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60792. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60793. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60794. *
  60795. * Returns the Mesh.
  60796. */
  60797. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60798. if (this.sourceMesh) {
  60799. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60800. }
  60801. return this.sourceMesh;
  60802. };
  60803. /**
  60804. * Sets the mesh indices.
  60805. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60806. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60807. * This method creates a new index buffer each call.
  60808. * Returns the Mesh.
  60809. */
  60810. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60811. if (totalVertices === void 0) { totalVertices = null; }
  60812. if (this.sourceMesh) {
  60813. this.sourceMesh.setIndices(indices, totalVertices);
  60814. }
  60815. return this.sourceMesh;
  60816. };
  60817. /**
  60818. * Boolean : True if the mesh owns the requested kind of data.
  60819. */
  60820. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60821. return this._sourceMesh.isVerticesDataPresent(kind);
  60822. };
  60823. /**
  60824. * Returns an array of indices (IndicesArray).
  60825. */
  60826. InstancedMesh.prototype.getIndices = function () {
  60827. return this._sourceMesh.getIndices();
  60828. };
  60829. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60830. get: function () {
  60831. return this._sourceMesh._positions;
  60832. },
  60833. enumerable: true,
  60834. configurable: true
  60835. });
  60836. /**
  60837. * Sets a new updated BoundingInfo to the mesh.
  60838. * Returns the mesh.
  60839. */
  60840. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60841. var meshBB = this._sourceMesh.getBoundingInfo();
  60842. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60843. this._updateBoundingInfo();
  60844. return this;
  60845. };
  60846. InstancedMesh.prototype._preActivate = function () {
  60847. if (this._currentLOD) {
  60848. this._currentLOD._preActivate();
  60849. }
  60850. return this;
  60851. };
  60852. InstancedMesh.prototype._activate = function (renderId) {
  60853. if (this._currentLOD) {
  60854. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60855. }
  60856. return this;
  60857. };
  60858. /**
  60859. * Returns the current associated LOD AbstractMesh.
  60860. */
  60861. InstancedMesh.prototype.getLOD = function (camera) {
  60862. if (!camera) {
  60863. return this;
  60864. }
  60865. var boundingInfo = this.getBoundingInfo();
  60866. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60867. if (this._currentLOD === this.sourceMesh) {
  60868. return this;
  60869. }
  60870. return this._currentLOD;
  60871. };
  60872. InstancedMesh.prototype._syncSubMeshes = function () {
  60873. this.releaseSubMeshes();
  60874. if (this._sourceMesh.subMeshes) {
  60875. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60876. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60877. }
  60878. }
  60879. return this;
  60880. };
  60881. InstancedMesh.prototype._generatePointsArray = function () {
  60882. return this._sourceMesh._generatePointsArray();
  60883. };
  60884. /**
  60885. * Creates a new InstancedMesh from the current mesh.
  60886. * - name (string) : the cloned mesh name
  60887. * - newParent (optional Node) : the optional Node to parent the clone to.
  60888. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60889. *
  60890. * Returns the clone.
  60891. */
  60892. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60893. var result = this._sourceMesh.createInstance(name);
  60894. // Deep copy
  60895. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60896. // Bounding info
  60897. this.refreshBoundingInfo();
  60898. // Parent
  60899. if (newParent) {
  60900. result.parent = newParent;
  60901. }
  60902. if (!doNotCloneChildren) {
  60903. // Children
  60904. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60905. var mesh = this.getScene().meshes[index];
  60906. if (mesh.parent === this) {
  60907. mesh.clone(mesh.name, result);
  60908. }
  60909. }
  60910. }
  60911. result.computeWorldMatrix(true);
  60912. return result;
  60913. };
  60914. /**
  60915. * Disposes the InstancedMesh.
  60916. * Returns nothing.
  60917. */
  60918. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60919. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60920. // Remove from mesh
  60921. var index = this._sourceMesh.instances.indexOf(this);
  60922. this._sourceMesh.instances.splice(index, 1);
  60923. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60924. };
  60925. return InstancedMesh;
  60926. }(BABYLON.AbstractMesh));
  60927. BABYLON.InstancedMesh = InstancedMesh;
  60928. })(BABYLON || (BABYLON = {}));
  60929. //# sourceMappingURL=babylon.instancedMesh.js.map
  60930. var BABYLON;
  60931. (function (BABYLON) {
  60932. var LinesMesh = /** @class */ (function (_super) {
  60933. __extends(LinesMesh, _super);
  60934. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60935. if (scene === void 0) { scene = null; }
  60936. if (parent === void 0) { parent = null; }
  60937. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60938. _this.useVertexColor = useVertexColor;
  60939. _this.useVertexAlpha = useVertexAlpha;
  60940. _this.color = new BABYLON.Color3(1, 1, 1);
  60941. _this.alpha = 1;
  60942. if (source) {
  60943. _this.color = source.color.clone();
  60944. _this.alpha = source.alpha;
  60945. _this.useVertexColor = source.useVertexColor;
  60946. _this.useVertexAlpha = source.useVertexAlpha;
  60947. }
  60948. _this._intersectionThreshold = 0.1;
  60949. var defines = [];
  60950. var options = {
  60951. attributes: [BABYLON.VertexBuffer.PositionKind],
  60952. uniforms: ["world", "viewProjection"],
  60953. needAlphaBlending: true,
  60954. defines: defines
  60955. };
  60956. if (useVertexAlpha === false) {
  60957. options.needAlphaBlending = false;
  60958. }
  60959. if (!useVertexColor) {
  60960. options.uniforms.push("color");
  60961. }
  60962. else {
  60963. options.defines.push("#define VERTEXCOLOR");
  60964. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60965. }
  60966. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60967. return _this;
  60968. }
  60969. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60970. /**
  60971. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60972. * This margin is expressed in world space coordinates, so its value may vary.
  60973. * Default value is 0.1
  60974. * @returns the intersection Threshold value.
  60975. */
  60976. get: function () {
  60977. return this._intersectionThreshold;
  60978. },
  60979. /**
  60980. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60981. * This margin is expressed in world space coordinates, so its value may vary.
  60982. * @param value the new threshold to apply
  60983. */
  60984. set: function (value) {
  60985. if (this._intersectionThreshold === value) {
  60986. return;
  60987. }
  60988. this._intersectionThreshold = value;
  60989. if (this.geometry) {
  60990. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60991. }
  60992. },
  60993. enumerable: true,
  60994. configurable: true
  60995. });
  60996. /**
  60997. * Returns the string "LineMesh"
  60998. */
  60999. LinesMesh.prototype.getClassName = function () {
  61000. return "LinesMesh";
  61001. };
  61002. Object.defineProperty(LinesMesh.prototype, "material", {
  61003. get: function () {
  61004. return this._colorShader;
  61005. },
  61006. set: function (value) {
  61007. // Do nothing
  61008. },
  61009. enumerable: true,
  61010. configurable: true
  61011. });
  61012. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61013. get: function () {
  61014. return false;
  61015. },
  61016. enumerable: true,
  61017. configurable: true
  61018. });
  61019. LinesMesh.prototype.createInstance = function (name) {
  61020. throw new Error("LinesMeshes do not support createInstance.");
  61021. };
  61022. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61023. if (!this._geometry) {
  61024. return this;
  61025. }
  61026. // VBOs
  61027. this._geometry._bind(this._colorShader.getEffect());
  61028. // Color
  61029. if (!this.useVertexColor) {
  61030. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61031. }
  61032. return this;
  61033. };
  61034. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61035. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61036. return this;
  61037. }
  61038. var engine = this.getScene().getEngine();
  61039. // Draw order
  61040. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61041. return this;
  61042. };
  61043. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61044. this._colorShader.dispose();
  61045. _super.prototype.dispose.call(this, doNotRecurse);
  61046. };
  61047. /**
  61048. * Returns a new LineMesh object cloned from the current one.
  61049. */
  61050. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61051. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61052. };
  61053. return LinesMesh;
  61054. }(BABYLON.Mesh));
  61055. BABYLON.LinesMesh = LinesMesh;
  61056. })(BABYLON || (BABYLON = {}));
  61057. //# sourceMappingURL=babylon.linesMesh.js.map
  61058. var BABYLON;
  61059. (function (BABYLON) {
  61060. /**
  61061. * Class containing static functions to help procedurally build meshes
  61062. */
  61063. var MeshBuilder = /** @class */ (function () {
  61064. function MeshBuilder() {
  61065. }
  61066. MeshBuilder.updateSideOrientation = function (orientation) {
  61067. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61068. return BABYLON.Mesh.DOUBLESIDE;
  61069. }
  61070. if (orientation === undefined || orientation === null) {
  61071. return BABYLON.Mesh.FRONTSIDE;
  61072. }
  61073. return orientation;
  61074. };
  61075. /**
  61076. * Creates a box mesh
  61077. * * The parameter `size` sets the size (float) of each box side (default 1)
  61078. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61079. * * 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)
  61080. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61081. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61082. * * 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
  61083. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61084. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61085. * @param name defines the name of the mesh
  61086. * @param options defines the options used to create the mesh
  61087. * @param scene defines the hosting scene
  61088. * @returns the box mesh
  61089. */
  61090. MeshBuilder.CreateBox = function (name, options, scene) {
  61091. if (scene === void 0) { scene = null; }
  61092. var box = new BABYLON.Mesh(name, scene);
  61093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61094. box._originalBuilderSideOrientation = options.sideOrientation;
  61095. var vertexData = BABYLON.VertexData.CreateBox(options);
  61096. vertexData.applyToMesh(box, options.updatable);
  61097. return box;
  61098. };
  61099. /**
  61100. * Creates a sphere mesh
  61101. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61102. * * 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`)
  61103. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61104. * * 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
  61105. * * 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)
  61106. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61107. * * 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
  61108. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61109. * @param name defines the name of the mesh
  61110. * @param options defines the options used to create the mesh
  61111. * @param scene defines the hosting scene
  61112. * @returns the sphere mesh
  61113. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61114. */
  61115. MeshBuilder.CreateSphere = function (name, options, scene) {
  61116. var sphere = new BABYLON.Mesh(name, scene);
  61117. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61118. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61119. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61120. vertexData.applyToMesh(sphere, options.updatable);
  61121. return sphere;
  61122. };
  61123. /**
  61124. * Creates a plane polygonal mesh. By default, this is a disc
  61125. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61126. * * 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
  61127. * * 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
  61128. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61129. * * 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
  61130. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61131. * @param name defines the name of the mesh
  61132. * @param options defines the options used to create the mesh
  61133. * @param scene defines the hosting scene
  61134. * @returns the plane polygonal mesh
  61135. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61136. */
  61137. MeshBuilder.CreateDisc = function (name, options, scene) {
  61138. if (scene === void 0) { scene = null; }
  61139. var disc = new BABYLON.Mesh(name, scene);
  61140. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61141. disc._originalBuilderSideOrientation = options.sideOrientation;
  61142. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61143. vertexData.applyToMesh(disc, options.updatable);
  61144. return disc;
  61145. };
  61146. /**
  61147. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61148. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61149. * * 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`)
  61150. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61151. * * 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
  61152. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61153. * * 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
  61154. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61155. * @param name defines the name of the mesh
  61156. * @param options defines the options used to create the mesh
  61157. * @param scene defines the hosting scene
  61158. * @returns the icosahedron mesh
  61159. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61160. */
  61161. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61162. var sphere = new BABYLON.Mesh(name, scene);
  61163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61164. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61165. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61166. vertexData.applyToMesh(sphere, options.updatable);
  61167. return sphere;
  61168. };
  61169. ;
  61170. /**
  61171. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61172. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61173. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61174. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61175. * * 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
  61176. * * 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
  61177. * * 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
  61178. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61179. * * 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
  61180. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61181. * * 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
  61182. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61183. * * 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
  61184. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61185. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61186. * @param name defines the name of the mesh
  61187. * @param options defines the options used to create the mesh
  61188. * @param scene defines the hosting scene
  61189. * @returns the ribbon mesh
  61190. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61191. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61192. */
  61193. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61194. if (scene === void 0) { scene = null; }
  61195. var pathArray = options.pathArray;
  61196. var closeArray = options.closeArray;
  61197. var closePath = options.closePath;
  61198. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61199. var instance = options.instance;
  61200. var updatable = options.updatable;
  61201. if (instance) { // existing ribbon instance update
  61202. // positionFunction : ribbon case
  61203. // only pathArray and sideOrientation parameters are taken into account for positions update
  61204. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61205. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61206. var positionFunction = function (positions) {
  61207. var minlg = pathArray[0].length;
  61208. var i = 0;
  61209. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61210. for (var si = 1; si <= ns; si++) {
  61211. for (var p = 0; p < pathArray.length; p++) {
  61212. var path = pathArray[p];
  61213. var l = path.length;
  61214. minlg = (minlg < l) ? minlg : l;
  61215. var j = 0;
  61216. while (j < minlg) {
  61217. positions[i] = path[j].x;
  61218. positions[i + 1] = path[j].y;
  61219. positions[i + 2] = path[j].z;
  61220. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61221. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61222. }
  61223. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61224. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61225. }
  61226. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61227. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61228. }
  61229. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61230. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61231. }
  61232. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61233. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61234. }
  61235. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61236. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61237. }
  61238. j++;
  61239. i += 3;
  61240. }
  61241. if (instance._closePath) {
  61242. positions[i] = path[0].x;
  61243. positions[i + 1] = path[0].y;
  61244. positions[i + 2] = path[0].z;
  61245. i += 3;
  61246. }
  61247. }
  61248. }
  61249. };
  61250. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61251. positionFunction(positions);
  61252. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61253. instance._boundingInfo.update(instance._worldMatrix);
  61254. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61255. if (options.colors) {
  61256. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61257. for (var c = 0; c < options.colors.length; c++) {
  61258. colors[c * 4] = options.colors[c].r;
  61259. colors[c * 4 + 1] = options.colors[c].g;
  61260. colors[c * 4 + 2] = options.colors[c].b;
  61261. colors[c * 4 + 3] = options.colors[c].a;
  61262. }
  61263. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61264. }
  61265. if (options.uvs) {
  61266. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61267. for (var i = 0; i < options.uvs.length; i++) {
  61268. uvs[i * 2] = options.uvs[i].x;
  61269. uvs[i * 2 + 1] = options.uvs[i].y;
  61270. }
  61271. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61272. }
  61273. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61274. var indices = instance.getIndices();
  61275. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61276. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61277. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61278. if (instance._closePath) {
  61279. var indexFirst = 0;
  61280. var indexLast = 0;
  61281. for (var p = 0; p < pathArray.length; p++) {
  61282. indexFirst = instance._idx[p] * 3;
  61283. if (p + 1 < pathArray.length) {
  61284. indexLast = (instance._idx[p + 1] - 1) * 3;
  61285. }
  61286. else {
  61287. indexLast = normals.length - 3;
  61288. }
  61289. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61290. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61291. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61292. normals[indexLast] = normals[indexFirst];
  61293. normals[indexLast + 1] = normals[indexFirst + 1];
  61294. normals[indexLast + 2] = normals[indexFirst + 2];
  61295. }
  61296. }
  61297. if (!(instance.areNormalsFrozen)) {
  61298. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61299. }
  61300. }
  61301. return instance;
  61302. }
  61303. else { // new ribbon creation
  61304. var ribbon = new BABYLON.Mesh(name, scene);
  61305. ribbon._originalBuilderSideOrientation = sideOrientation;
  61306. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61307. if (closePath) {
  61308. ribbon._idx = vertexData._idx;
  61309. }
  61310. ribbon._closePath = closePath;
  61311. ribbon._closeArray = closeArray;
  61312. vertexData.applyToMesh(ribbon, updatable);
  61313. return ribbon;
  61314. }
  61315. };
  61316. /**
  61317. * Creates a cylinder or a cone mesh
  61318. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61319. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61320. * * 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.
  61321. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61322. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61323. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61324. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61325. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61326. * * 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).
  61327. * * 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
  61328. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61329. * * 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
  61330. * * 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.
  61331. * * If `enclose` is false, a ring surface is one element.
  61332. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61333. * * 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
  61334. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61335. * * 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
  61336. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61337. * @param name defines the name of the mesh
  61338. * @param options defines the options used to create the mesh
  61339. * @param scene defines the hosting scene
  61340. * @returns the cylinder mesh
  61341. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61342. */
  61343. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61344. var cylinder = new BABYLON.Mesh(name, scene);
  61345. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61346. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61347. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61348. vertexData.applyToMesh(cylinder, options.updatable);
  61349. return cylinder;
  61350. };
  61351. /**
  61352. * Creates a torus mesh
  61353. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61354. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61355. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61356. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61357. * * 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
  61358. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61359. * @param name defines the name of the mesh
  61360. * @param options defines the options used to create the mesh
  61361. * @param scene defines the hosting scene
  61362. * @returns the torus mesh
  61363. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61364. */
  61365. MeshBuilder.CreateTorus = function (name, options, scene) {
  61366. var torus = new BABYLON.Mesh(name, scene);
  61367. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61368. torus._originalBuilderSideOrientation = options.sideOrientation;
  61369. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61370. vertexData.applyToMesh(torus, options.updatable);
  61371. return torus;
  61372. };
  61373. /**
  61374. * Creates a torus knot mesh
  61375. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61376. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61377. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61378. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61379. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61380. * * 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
  61381. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61382. * @param name defines the name of the mesh
  61383. * @param options defines the options used to create the mesh
  61384. * @param scene defines the hosting scene
  61385. * @returns the torus knot mesh
  61386. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61387. */
  61388. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61389. var torusKnot = new BABYLON.Mesh(name, scene);
  61390. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61391. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61392. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61393. vertexData.applyToMesh(torusKnot, options.updatable);
  61394. return torusKnot;
  61395. };
  61396. /**
  61397. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61398. * * 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
  61399. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61400. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61401. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61402. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61403. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61404. * * 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
  61405. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61406. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61407. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61408. * @param name defines the name of the new line system
  61409. * @param options defines the options used to create the line system
  61410. * @param scene defines the hosting scene
  61411. * @returns a new line system mesh
  61412. */
  61413. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61414. var instance = options.instance;
  61415. var lines = options.lines;
  61416. var colors = options.colors;
  61417. if (instance) { // lines update
  61418. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61419. var vertexColor;
  61420. var lineColors;
  61421. if (colors) {
  61422. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61423. }
  61424. var i = 0;
  61425. var c = 0;
  61426. for (var l = 0; l < lines.length; l++) {
  61427. var points = lines[l];
  61428. for (var p = 0; p < points.length; p++) {
  61429. positions[i] = points[p].x;
  61430. positions[i + 1] = points[p].y;
  61431. positions[i + 2] = points[p].z;
  61432. if (colors && vertexColor) {
  61433. lineColors = colors[l];
  61434. vertexColor[c] = lineColors[p].r;
  61435. vertexColor[c + 1] = lineColors[p].g;
  61436. vertexColor[c + 2] = lineColors[p].b;
  61437. vertexColor[c + 3] = lineColors[p].a;
  61438. c += 4;
  61439. }
  61440. i += 3;
  61441. }
  61442. }
  61443. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61444. if (colors && vertexColor) {
  61445. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61446. }
  61447. return instance;
  61448. }
  61449. // line system creation
  61450. var useVertexColor = (colors) ? true : false;
  61451. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61452. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61453. vertexData.applyToMesh(lineSystem, options.updatable);
  61454. return lineSystem;
  61455. };
  61456. /**
  61457. * Creates a line mesh
  61458. * 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
  61459. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61460. * * The parameter `points` is an array successive Vector3
  61461. * * 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
  61462. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61463. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61464. * * When updating an instance, remember that only point positions can change, not the number of points
  61465. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61466. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61467. * @param name defines the name of the new line system
  61468. * @param options defines the options used to create the line system
  61469. * @param scene defines the hosting scene
  61470. * @returns a new line mesh
  61471. */
  61472. MeshBuilder.CreateLines = function (name, options, scene) {
  61473. if (scene === void 0) { scene = null; }
  61474. var colors = (options.colors) ? [options.colors] : null;
  61475. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61476. return lines;
  61477. };
  61478. /**
  61479. * Creates a dashed line mesh
  61480. * * 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
  61481. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61482. * * The parameter `points` is an array successive Vector3
  61483. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61484. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61485. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61486. * * 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
  61487. * * When updating an instance, remember that only point positions can change, not the number of points
  61488. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61489. * @param name defines the name of the mesh
  61490. * @param options defines the options used to create the mesh
  61491. * @param scene defines the hosting scene
  61492. * @returns the dashed line mesh
  61493. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61494. */
  61495. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61496. if (scene === void 0) { scene = null; }
  61497. var points = options.points;
  61498. var instance = options.instance;
  61499. var gapSize = options.gapSize || 1;
  61500. var dashSize = options.dashSize || 3;
  61501. if (instance) { // dashed lines update
  61502. var positionFunction = function (positions) {
  61503. var curvect = BABYLON.Vector3.Zero();
  61504. var nbSeg = positions.length / 6;
  61505. var lg = 0;
  61506. var nb = 0;
  61507. var shft = 0;
  61508. var dashshft = 0;
  61509. var curshft = 0;
  61510. var p = 0;
  61511. var i = 0;
  61512. var j = 0;
  61513. for (i = 0; i < points.length - 1; i++) {
  61514. points[i + 1].subtractToRef(points[i], curvect);
  61515. lg += curvect.length();
  61516. }
  61517. shft = lg / nbSeg;
  61518. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61519. for (i = 0; i < points.length - 1; i++) {
  61520. points[i + 1].subtractToRef(points[i], curvect);
  61521. nb = Math.floor(curvect.length() / shft);
  61522. curvect.normalize();
  61523. j = 0;
  61524. while (j < nb && p < positions.length) {
  61525. curshft = shft * j;
  61526. positions[p] = points[i].x + curshft * curvect.x;
  61527. positions[p + 1] = points[i].y + curshft * curvect.y;
  61528. positions[p + 2] = points[i].z + curshft * curvect.z;
  61529. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61530. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61531. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61532. p += 6;
  61533. j++;
  61534. }
  61535. }
  61536. while (p < positions.length) {
  61537. positions[p] = points[i].x;
  61538. positions[p + 1] = points[i].y;
  61539. positions[p + 2] = points[i].z;
  61540. p += 3;
  61541. }
  61542. };
  61543. instance.updateMeshPositions(positionFunction, false);
  61544. return instance;
  61545. }
  61546. // dashed lines creation
  61547. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61548. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61549. vertexData.applyToMesh(dashedLines, options.updatable);
  61550. dashedLines.dashSize = dashSize;
  61551. dashedLines.gapSize = gapSize;
  61552. return dashedLines;
  61553. };
  61554. /**
  61555. * 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.
  61556. * * 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.
  61557. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61558. * * 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.
  61559. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61560. * * 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
  61561. * * 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
  61562. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61563. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61564. * * 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
  61565. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61566. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61567. * @param name defines the name of the mesh
  61568. * @param options defines the options used to create the mesh
  61569. * @param scene defines the hosting scene
  61570. * @returns the extruded shape mesh
  61571. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61572. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61573. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61574. */
  61575. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61576. if (scene === void 0) { scene = null; }
  61577. var path = options.path;
  61578. var shape = options.shape;
  61579. var scale = options.scale || 1;
  61580. var rotation = options.rotation || 0;
  61581. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61582. var updatable = options.updatable;
  61583. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61584. var instance = options.instance || null;
  61585. var invertUV = options.invertUV || false;
  61586. 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);
  61587. };
  61588. /**
  61589. * Creates an custom extruded shape mesh.
  61590. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61591. * * 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.
  61592. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61593. * * 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
  61594. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61595. * * 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
  61596. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61597. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61598. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61599. * * 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
  61600. * * 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
  61601. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61602. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61603. * * 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
  61604. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61605. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61606. * @param name defines the name of the mesh
  61607. * @param options defines the options used to create the mesh
  61608. * @param scene defines the hosting scene
  61609. * @returns the custom extruded shape mesh
  61610. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61611. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61612. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61613. */
  61614. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61615. var path = options.path;
  61616. var shape = options.shape;
  61617. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61618. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61619. var ribbonCloseArray = options.ribbonCloseArray || false;
  61620. var ribbonClosePath = options.ribbonClosePath || false;
  61621. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61622. var updatable = options.updatable;
  61623. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61624. var instance = options.instance;
  61625. var invertUV = options.invertUV || false;
  61626. 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);
  61627. };
  61628. /**
  61629. * Creates lathe mesh.
  61630. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61631. * * 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
  61632. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61633. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61634. * * 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
  61635. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61636. * * 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
  61637. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61638. * * 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
  61639. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61641. * @param name defines the name of the mesh
  61642. * @param options defines the options used to create the mesh
  61643. * @param scene defines the hosting scene
  61644. * @returns the lathe mesh
  61645. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61646. */
  61647. MeshBuilder.CreateLathe = function (name, options, scene) {
  61648. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61649. var closed = (options.closed === undefined) ? true : options.closed;
  61650. var shape = options.shape;
  61651. var radius = options.radius || 1;
  61652. var tessellation = options.tessellation || 64;
  61653. var updatable = options.updatable;
  61654. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61655. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61656. var pi2 = Math.PI * 2;
  61657. var paths = new Array();
  61658. var invertUV = options.invertUV || false;
  61659. var i = 0;
  61660. var p = 0;
  61661. var step = pi2 / tessellation * arc;
  61662. var rotated;
  61663. var path = new Array();
  61664. for (i = 0; i <= tessellation; i++) {
  61665. var path = [];
  61666. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61667. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61668. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61669. }
  61670. for (p = 0; p < shape.length; p++) {
  61671. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61672. path.push(rotated);
  61673. }
  61674. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61675. 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));
  61676. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61677. }
  61678. paths.push(path);
  61679. }
  61680. // lathe ribbon
  61681. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61682. return lathe;
  61683. };
  61684. /**
  61685. * Creates a plane mesh
  61686. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61687. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61688. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61689. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61690. * * 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
  61691. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61692. * @param name defines the name of the mesh
  61693. * @param options defines the options used to create the mesh
  61694. * @param scene defines the hosting scene
  61695. * @returns the plane mesh
  61696. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61697. */
  61698. MeshBuilder.CreatePlane = function (name, options, scene) {
  61699. var plane = new BABYLON.Mesh(name, scene);
  61700. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61701. plane._originalBuilderSideOrientation = options.sideOrientation;
  61702. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61703. vertexData.applyToMesh(plane, options.updatable);
  61704. if (options.sourcePlane) {
  61705. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61706. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61707. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61708. plane.rotate(vectorProduct, product);
  61709. }
  61710. return plane;
  61711. };
  61712. /**
  61713. * Creates a ground mesh
  61714. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61715. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61716. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61717. * @param name defines the name of the mesh
  61718. * @param options defines the options used to create the mesh
  61719. * @param scene defines the hosting scene
  61720. * @returns the ground mesh
  61721. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61722. */
  61723. MeshBuilder.CreateGround = function (name, options, scene) {
  61724. var ground = new BABYLON.GroundMesh(name, scene);
  61725. ground._setReady(false);
  61726. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61727. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61728. ground._width = options.width || 1;
  61729. ground._height = options.height || 1;
  61730. ground._maxX = ground._width / 2;
  61731. ground._maxZ = ground._height / 2;
  61732. ground._minX = -ground._maxX;
  61733. ground._minZ = -ground._maxZ;
  61734. var vertexData = BABYLON.VertexData.CreateGround(options);
  61735. vertexData.applyToMesh(ground, options.updatable);
  61736. ground._setReady(true);
  61737. return ground;
  61738. };
  61739. /**
  61740. * Creates a tiled ground mesh
  61741. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61742. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61743. * * 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
  61744. * * 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
  61745. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61746. * @param name defines the name of the mesh
  61747. * @param options defines the options used to create the mesh
  61748. * @param scene defines the hosting scene
  61749. * @returns the tiled ground mesh
  61750. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61751. */
  61752. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61753. var tiledGround = new BABYLON.Mesh(name, scene);
  61754. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61755. vertexData.applyToMesh(tiledGround, options.updatable);
  61756. return tiledGround;
  61757. };
  61758. /**
  61759. * Creates a ground mesh from a height map
  61760. * * The parameter `url` sets the URL of the height map image resource.
  61761. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61762. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61763. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61764. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61765. * * 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.
  61766. * * 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).
  61767. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61768. * @param name defines the name of the mesh
  61769. * @param url defines the url to the height map
  61770. * @param options defines the options used to create the mesh
  61771. * @param scene defines the hosting scene
  61772. * @returns the ground mesh
  61773. * @see http://doc.babylonjs.com/babylon101/height_map
  61774. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61775. */
  61776. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61777. var width = options.width || 10.0;
  61778. var height = options.height || 10.0;
  61779. var subdivisions = options.subdivisions || 1 | 0;
  61780. var minHeight = options.minHeight || 0.0;
  61781. var maxHeight = options.maxHeight || 1.0;
  61782. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61783. var updatable = options.updatable;
  61784. var onReady = options.onReady;
  61785. var ground = new BABYLON.GroundMesh(name, scene);
  61786. ground._subdivisionsX = subdivisions;
  61787. ground._subdivisionsY = subdivisions;
  61788. ground._width = width;
  61789. ground._height = height;
  61790. ground._maxX = ground._width / 2.0;
  61791. ground._maxZ = ground._height / 2.0;
  61792. ground._minX = -ground._maxX;
  61793. ground._minZ = -ground._maxZ;
  61794. ground._setReady(false);
  61795. var onload = function (img) {
  61796. // Getting height map data
  61797. var canvas = document.createElement("canvas");
  61798. var context = canvas.getContext("2d");
  61799. if (!context) {
  61800. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61801. }
  61802. if (scene.isDisposed) {
  61803. return;
  61804. }
  61805. var bufferWidth = img.width;
  61806. var bufferHeight = img.height;
  61807. canvas.width = bufferWidth;
  61808. canvas.height = bufferHeight;
  61809. context.drawImage(img, 0, 0);
  61810. // Create VertexData from map data
  61811. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61812. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61813. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61814. width: width, height: height,
  61815. subdivisions: subdivisions,
  61816. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61817. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61818. });
  61819. vertexData.applyToMesh(ground, updatable);
  61820. //execute ready callback, if set
  61821. if (onReady) {
  61822. onReady(ground);
  61823. }
  61824. ground._setReady(true);
  61825. };
  61826. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61827. return ground;
  61828. };
  61829. /**
  61830. * Creates a polygon mesh
  61831. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61832. * * 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
  61833. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61834. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61835. * * 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)
  61836. * * Remember you can only change the shape positions, not their number when updating a polygon
  61837. * @param name defines the name of the mesh
  61838. * @param options defines the options used to create the mesh
  61839. * @param scene defines the hosting scene
  61840. * @returns the polygon mesh
  61841. */
  61842. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61843. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61844. var shape = options.shape;
  61845. var holes = options.holes || [];
  61846. var depth = options.depth || 0;
  61847. var contours = [];
  61848. var hole = [];
  61849. for (var i = 0; i < shape.length; i++) {
  61850. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61851. }
  61852. var epsilon = 0.00000001;
  61853. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61854. contours.pop();
  61855. }
  61856. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61857. for (var hNb = 0; hNb < holes.length; hNb++) {
  61858. hole = [];
  61859. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61860. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61861. }
  61862. polygonTriangulation.addHole(hole);
  61863. }
  61864. var polygon = polygonTriangulation.build(options.updatable, depth);
  61865. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61866. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61867. vertexData.applyToMesh(polygon, options.updatable);
  61868. return polygon;
  61869. };
  61870. ;
  61871. /**
  61872. * Creates an extruded polygon mesh, with depth in the Y direction.
  61873. * * 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)
  61874. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61875. * @param name defines the name of the mesh
  61876. * @param options defines the options used to create the mesh
  61877. * @param scene defines the hosting scene
  61878. * @returns the polygon mesh
  61879. */
  61880. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61881. return MeshBuilder.CreatePolygon(name, options, scene);
  61882. };
  61883. ;
  61884. /**
  61885. * Creates a tube mesh.
  61886. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61887. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61888. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61889. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61890. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61891. * * 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)
  61892. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61893. * * 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
  61894. * * 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
  61895. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61896. * * 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
  61897. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61898. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61899. * @param name defines the name of the mesh
  61900. * @param options defines the options used to create the mesh
  61901. * @param scene defines the hosting scene
  61902. * @returns the tube mesh
  61903. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61904. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61905. */
  61906. MeshBuilder.CreateTube = function (name, options, scene) {
  61907. var path = options.path;
  61908. var instance = options.instance;
  61909. var radius = 1.0;
  61910. if (instance) {
  61911. radius = instance.radius;
  61912. }
  61913. if (options.radius !== undefined) {
  61914. radius = options.radius;
  61915. }
  61916. ;
  61917. var tessellation = options.tessellation || 64 | 0;
  61918. var radiusFunction = options.radiusFunction || null;
  61919. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61920. var invertUV = options.invertUV || false;
  61921. var updatable = options.updatable;
  61922. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61923. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61924. // tube geometry
  61925. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61926. var tangents = path3D.getTangents();
  61927. var normals = path3D.getNormals();
  61928. var distances = path3D.getDistances();
  61929. var pi2 = Math.PI * 2;
  61930. var step = pi2 / tessellation * arc;
  61931. var returnRadius = function () { return radius; };
  61932. var radiusFunctionFinal = radiusFunction || returnRadius;
  61933. var circlePath;
  61934. var rad;
  61935. var normal;
  61936. var rotated;
  61937. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61938. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61939. for (var i = 0; i < path.length; i++) {
  61940. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61941. circlePath = Array(); // current circle array
  61942. normal = normals[i]; // current normal
  61943. for (var t = 0; t < tessellation; t++) {
  61944. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61945. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61946. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61947. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61948. circlePath[t] = rotated;
  61949. }
  61950. circlePaths[index] = circlePath;
  61951. index++;
  61952. }
  61953. // cap
  61954. var capPath = function (nbPoints, pathIndex) {
  61955. var pointCap = Array();
  61956. for (var i = 0; i < nbPoints; i++) {
  61957. pointCap.push(path[pathIndex]);
  61958. }
  61959. return pointCap;
  61960. };
  61961. switch (cap) {
  61962. case BABYLON.Mesh.NO_CAP:
  61963. break;
  61964. case BABYLON.Mesh.CAP_START:
  61965. circlePaths[0] = capPath(tessellation, 0);
  61966. circlePaths[1] = circlePaths[2].slice(0);
  61967. break;
  61968. case BABYLON.Mesh.CAP_END:
  61969. circlePaths[index] = circlePaths[index - 1].slice(0);
  61970. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61971. break;
  61972. case BABYLON.Mesh.CAP_ALL:
  61973. circlePaths[0] = capPath(tessellation, 0);
  61974. circlePaths[1] = circlePaths[2].slice(0);
  61975. circlePaths[index] = circlePaths[index - 1].slice(0);
  61976. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61977. break;
  61978. default:
  61979. break;
  61980. }
  61981. return circlePaths;
  61982. };
  61983. var path3D;
  61984. var pathArray;
  61985. if (instance) { // tube update
  61986. var arc = options.arc || instance.arc;
  61987. path3D = (instance.path3D).update(path);
  61988. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61989. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61990. instance.path3D = path3D;
  61991. instance.pathArray = pathArray;
  61992. instance.arc = arc;
  61993. instance.radius = radius;
  61994. return instance;
  61995. }
  61996. // tube creation
  61997. path3D = new BABYLON.Path3D(path);
  61998. var newPathArray = new Array();
  61999. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62000. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62001. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62002. tube.pathArray = pathArray;
  62003. tube.path3D = path3D;
  62004. tube.tessellation = tessellation;
  62005. tube.cap = cap;
  62006. tube.arc = options.arc;
  62007. tube.radius = radius;
  62008. return tube;
  62009. };
  62010. /**
  62011. * Creates a polyhedron mesh
  62012. * * 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
  62013. * * The parameter `size` (positive float, default 1) sets the polygon size
  62014. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62015. * * 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`
  62016. * * 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
  62017. * * 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)`)
  62018. * * 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
  62019. * * 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
  62020. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62021. * * 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
  62022. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62023. * @param name defines the name of the mesh
  62024. * @param options defines the options used to create the mesh
  62025. * @param scene defines the hosting scene
  62026. * @returns the polyhedron mesh
  62027. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62028. */
  62029. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62030. var polyhedron = new BABYLON.Mesh(name, scene);
  62031. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62032. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62033. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62034. vertexData.applyToMesh(polyhedron, options.updatable);
  62035. return polyhedron;
  62036. };
  62037. /**
  62038. * Creates a decal mesh.
  62039. * 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
  62040. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62041. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62042. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62043. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62044. * @param name defines the name of the mesh
  62045. * @param sourceMesh defines the mesh where the decal must be applied
  62046. * @param options defines the options used to create the mesh
  62047. * @param scene defines the hosting scene
  62048. * @returns the decal mesh
  62049. * @see http://doc.babylonjs.com/how_to/decals
  62050. */
  62051. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62052. var indices = sourceMesh.getIndices();
  62053. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62054. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62055. var position = options.position || BABYLON.Vector3.Zero();
  62056. var normal = options.normal || BABYLON.Vector3.Up();
  62057. var size = options.size || BABYLON.Vector3.One();
  62058. var angle = options.angle || 0;
  62059. // Getting correct rotation
  62060. if (!normal) {
  62061. var target = new BABYLON.Vector3(0, 0, 1);
  62062. var camera = sourceMesh.getScene().activeCamera;
  62063. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62064. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62065. }
  62066. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62067. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62068. var pitch = Math.atan2(normal.y, len);
  62069. // Matrix
  62070. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62071. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62072. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62073. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62074. var vertexData = new BABYLON.VertexData();
  62075. vertexData.indices = [];
  62076. vertexData.positions = [];
  62077. vertexData.normals = [];
  62078. vertexData.uvs = [];
  62079. var currentVertexDataIndex = 0;
  62080. var extractDecalVector3 = function (indexId) {
  62081. var result = new BABYLON.PositionNormalVertex();
  62082. if (!indices || !positions || !normals) {
  62083. return result;
  62084. }
  62085. var vertexId = indices[indexId];
  62086. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62087. // Send vector to decal local world
  62088. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62089. // Get normal
  62090. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62091. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62092. return result;
  62093. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62094. var clip = function (vertices, axis) {
  62095. if (vertices.length === 0) {
  62096. return vertices;
  62097. }
  62098. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62099. var clipVertices = function (v0, v1) {
  62100. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62101. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62102. };
  62103. var result = new Array();
  62104. for (var index = 0; index < vertices.length; index += 3) {
  62105. var v1Out;
  62106. var v2Out;
  62107. var v3Out;
  62108. var total = 0;
  62109. var nV1 = null;
  62110. var nV2 = null;
  62111. var nV3 = null;
  62112. var nV4 = null;
  62113. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62114. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62115. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62116. v1Out = d1 > 0;
  62117. v2Out = d2 > 0;
  62118. v3Out = d3 > 0;
  62119. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62120. switch (total) {
  62121. case 0:
  62122. result.push(vertices[index]);
  62123. result.push(vertices[index + 1]);
  62124. result.push(vertices[index + 2]);
  62125. break;
  62126. case 1:
  62127. if (v1Out) {
  62128. nV1 = vertices[index + 1];
  62129. nV2 = vertices[index + 2];
  62130. nV3 = clipVertices(vertices[index], nV1);
  62131. nV4 = clipVertices(vertices[index], nV2);
  62132. }
  62133. if (v2Out) {
  62134. nV1 = vertices[index];
  62135. nV2 = vertices[index + 2];
  62136. nV3 = clipVertices(vertices[index + 1], nV1);
  62137. nV4 = clipVertices(vertices[index + 1], nV2);
  62138. result.push(nV3);
  62139. result.push(nV2.clone());
  62140. result.push(nV1.clone());
  62141. result.push(nV2.clone());
  62142. result.push(nV3.clone());
  62143. result.push(nV4);
  62144. break;
  62145. }
  62146. if (v3Out) {
  62147. nV1 = vertices[index];
  62148. nV2 = vertices[index + 1];
  62149. nV3 = clipVertices(vertices[index + 2], nV1);
  62150. nV4 = clipVertices(vertices[index + 2], nV2);
  62151. }
  62152. if (nV1 && nV2 && nV3 && nV4) {
  62153. result.push(nV1.clone());
  62154. result.push(nV2.clone());
  62155. result.push(nV3);
  62156. result.push(nV4);
  62157. result.push(nV3.clone());
  62158. result.push(nV2.clone());
  62159. }
  62160. break;
  62161. case 2:
  62162. if (!v1Out) {
  62163. nV1 = vertices[index].clone();
  62164. nV2 = clipVertices(nV1, vertices[index + 1]);
  62165. nV3 = clipVertices(nV1, vertices[index + 2]);
  62166. result.push(nV1);
  62167. result.push(nV2);
  62168. result.push(nV3);
  62169. }
  62170. if (!v2Out) {
  62171. nV1 = vertices[index + 1].clone();
  62172. nV2 = clipVertices(nV1, vertices[index + 2]);
  62173. nV3 = clipVertices(nV1, vertices[index]);
  62174. result.push(nV1);
  62175. result.push(nV2);
  62176. result.push(nV3);
  62177. }
  62178. if (!v3Out) {
  62179. nV1 = vertices[index + 2].clone();
  62180. nV2 = clipVertices(nV1, vertices[index]);
  62181. nV3 = clipVertices(nV1, vertices[index + 1]);
  62182. result.push(nV1);
  62183. result.push(nV2);
  62184. result.push(nV3);
  62185. }
  62186. break;
  62187. case 3:
  62188. break;
  62189. }
  62190. }
  62191. return result;
  62192. };
  62193. for (var index = 0; index < indices.length; index += 3) {
  62194. var faceVertices = new Array();
  62195. faceVertices.push(extractDecalVector3(index));
  62196. faceVertices.push(extractDecalVector3(index + 1));
  62197. faceVertices.push(extractDecalVector3(index + 2));
  62198. // Clip
  62199. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62200. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62201. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62202. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62203. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62204. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62205. if (faceVertices.length === 0) {
  62206. continue;
  62207. }
  62208. // Add UVs and get back to world
  62209. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62210. var vertex = faceVertices[vIndex];
  62211. //TODO check for Int32Array | Uint32Array | Uint16Array
  62212. vertexData.indices.push(currentVertexDataIndex);
  62213. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62214. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62215. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62216. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62217. currentVertexDataIndex++;
  62218. }
  62219. }
  62220. // Return mesh
  62221. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62222. vertexData.applyToMesh(decal);
  62223. decal.position = position.clone();
  62224. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62225. return decal;
  62226. };
  62227. // Privates
  62228. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62229. // extrusion geometry
  62230. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62231. var tangents = path3D.getTangents();
  62232. var normals = path3D.getNormals();
  62233. var binormals = path3D.getBinormals();
  62234. var distances = path3D.getDistances();
  62235. var angle = 0;
  62236. var returnScale = function () { return scale !== null ? scale : 1; };
  62237. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62238. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62239. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62240. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62241. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62242. for (var i = 0; i < curve.length; i++) {
  62243. var shapePath = new Array();
  62244. var angleStep = rotate(i, distances[i]);
  62245. var scaleRatio = scl(i, distances[i]);
  62246. for (var p = 0; p < shape.length; p++) {
  62247. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62248. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62249. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62250. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62251. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62252. shapePath[p] = rotated;
  62253. }
  62254. shapePaths[index] = shapePath;
  62255. angle += angleStep;
  62256. index++;
  62257. }
  62258. // cap
  62259. var capPath = function (shapePath) {
  62260. var pointCap = Array();
  62261. var barycenter = BABYLON.Vector3.Zero();
  62262. var i;
  62263. for (i = 0; i < shapePath.length; i++) {
  62264. barycenter.addInPlace(shapePath[i]);
  62265. }
  62266. barycenter.scaleInPlace(1.0 / shapePath.length);
  62267. for (i = 0; i < shapePath.length; i++) {
  62268. pointCap.push(barycenter);
  62269. }
  62270. return pointCap;
  62271. };
  62272. switch (cap) {
  62273. case BABYLON.Mesh.NO_CAP:
  62274. break;
  62275. case BABYLON.Mesh.CAP_START:
  62276. shapePaths[0] = capPath(shapePaths[2]);
  62277. shapePaths[1] = shapePaths[2];
  62278. break;
  62279. case BABYLON.Mesh.CAP_END:
  62280. shapePaths[index] = shapePaths[index - 1];
  62281. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62282. break;
  62283. case BABYLON.Mesh.CAP_ALL:
  62284. shapePaths[0] = capPath(shapePaths[2]);
  62285. shapePaths[1] = shapePaths[2];
  62286. shapePaths[index] = shapePaths[index - 1];
  62287. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62288. break;
  62289. default:
  62290. break;
  62291. }
  62292. return shapePaths;
  62293. };
  62294. var path3D;
  62295. var pathArray;
  62296. if (instance) { // instance update
  62297. path3D = (instance.path3D).update(curve);
  62298. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62299. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62300. return instance;
  62301. }
  62302. // extruded shape creation
  62303. path3D = new BABYLON.Path3D(curve);
  62304. var newShapePaths = new Array();
  62305. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62306. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62307. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62308. extrudedGeneric.pathArray = pathArray;
  62309. extrudedGeneric.path3D = path3D;
  62310. extrudedGeneric.cap = cap;
  62311. return extrudedGeneric;
  62312. };
  62313. return MeshBuilder;
  62314. }());
  62315. BABYLON.MeshBuilder = MeshBuilder;
  62316. })(BABYLON || (BABYLON = {}));
  62317. //# sourceMappingURL=babylon.meshBuilder.js.map
  62318. var BABYLON;
  62319. (function (BABYLON) {
  62320. /**
  62321. * Draco compression (https://google.github.io/draco/)
  62322. *
  62323. * This class wraps the Draco module.
  62324. *
  62325. * **Encoder**
  62326. *
  62327. * The encoder is not currently implemented.
  62328. *
  62329. * **Decoder**
  62330. *
  62331. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62332. *
  62333. * To update the configuration, use the following code:
  62334. * ```javascript
  62335. * BABYLON.DracoCompression.Configuration = {
  62336. * decoder: {
  62337. * wasmUrl: "<url to the WebAssembly library>",
  62338. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62339. * fallbackUrl: "<url to the fallback JavaScript library>",
  62340. * }
  62341. * };
  62342. * ```
  62343. *
  62344. * 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.
  62345. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62346. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62347. *
  62348. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62349. * ```javascript
  62350. * var dracoCompression = new BABYLON.DracoCompression();
  62351. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62352. * [BABYLON.VertexBuffer.PositionKind]: 0
  62353. * });
  62354. * ```
  62355. *
  62356. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62357. */
  62358. var DracoCompression = /** @class */ (function () {
  62359. /**
  62360. * Constructor
  62361. */
  62362. function DracoCompression() {
  62363. }
  62364. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62365. /**
  62366. * Returns true if the decoder is available.
  62367. */
  62368. get: function () {
  62369. if (typeof DracoDecoderModule !== "undefined") {
  62370. return true;
  62371. }
  62372. var decoder = DracoCompression.Configuration.decoder;
  62373. if (decoder) {
  62374. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62375. return true;
  62376. }
  62377. if (decoder.fallbackUrl) {
  62378. return true;
  62379. }
  62380. }
  62381. return false;
  62382. },
  62383. enumerable: true,
  62384. configurable: true
  62385. });
  62386. /**
  62387. * Stop all async operations and release resources.
  62388. */
  62389. DracoCompression.prototype.dispose = function () {
  62390. };
  62391. /**
  62392. * Decode Draco compressed mesh data to vertex data.
  62393. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62394. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62395. * @returns A promise that resolves with the decoded vertex data
  62396. */
  62397. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62398. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62399. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62400. var module = wrappedModule.module;
  62401. var vertexData = new BABYLON.VertexData();
  62402. var buffer = new module.DecoderBuffer();
  62403. buffer.Init(dataView, dataView.byteLength);
  62404. var decoder = new module.Decoder();
  62405. var geometry;
  62406. var status;
  62407. try {
  62408. var type = decoder.GetEncodedGeometryType(buffer);
  62409. switch (type) {
  62410. case module.TRIANGULAR_MESH:
  62411. geometry = new module.Mesh();
  62412. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62413. break;
  62414. case module.POINT_CLOUD:
  62415. geometry = new module.PointCloud();
  62416. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62417. break;
  62418. default:
  62419. throw new Error("Invalid geometry type " + type);
  62420. }
  62421. if (!status.ok() || !geometry.ptr) {
  62422. throw new Error(status.error_msg());
  62423. }
  62424. var numPoints = geometry.num_points();
  62425. if (type === module.TRIANGULAR_MESH) {
  62426. var numFaces = geometry.num_faces();
  62427. var faceIndices = new module.DracoInt32Array();
  62428. try {
  62429. var indices = new Uint32Array(numFaces * 3);
  62430. for (var i = 0; i < numFaces; i++) {
  62431. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62432. var offset = i * 3;
  62433. indices[offset + 0] = faceIndices.GetValue(0);
  62434. indices[offset + 1] = faceIndices.GetValue(1);
  62435. indices[offset + 2] = faceIndices.GetValue(2);
  62436. }
  62437. vertexData.indices = indices;
  62438. }
  62439. finally {
  62440. module.destroy(faceIndices);
  62441. }
  62442. }
  62443. for (var kind in attributes) {
  62444. var uniqueId = attributes[kind];
  62445. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62446. var dracoData = new module.DracoFloat32Array();
  62447. try {
  62448. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62449. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62450. for (var i = 0; i < babylonData.length; i++) {
  62451. babylonData[i] = dracoData.GetValue(i);
  62452. }
  62453. vertexData.set(babylonData, kind);
  62454. }
  62455. finally {
  62456. module.destroy(dracoData);
  62457. }
  62458. }
  62459. }
  62460. finally {
  62461. if (geometry) {
  62462. module.destroy(geometry);
  62463. }
  62464. module.destroy(decoder);
  62465. module.destroy(buffer);
  62466. }
  62467. return vertexData;
  62468. });
  62469. };
  62470. DracoCompression._GetDecoderModule = function () {
  62471. if (!DracoCompression._DecoderModulePromise) {
  62472. var promise = null;
  62473. var config_1 = {};
  62474. if (typeof DracoDecoderModule !== "undefined") {
  62475. promise = Promise.resolve();
  62476. }
  62477. else {
  62478. var decoder = DracoCompression.Configuration.decoder;
  62479. if (decoder) {
  62480. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62481. promise = Promise.all([
  62482. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62483. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62484. config_1.wasmBinary = data;
  62485. })
  62486. ]);
  62487. }
  62488. else if (decoder.fallbackUrl) {
  62489. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62490. }
  62491. }
  62492. }
  62493. if (!promise) {
  62494. throw new Error("Draco decoder module is not available");
  62495. }
  62496. DracoCompression._DecoderModulePromise = promise.then(function () {
  62497. return new Promise(function (resolve) {
  62498. config_1.onModuleLoaded = function (decoderModule) {
  62499. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62500. resolve({ module: decoderModule });
  62501. };
  62502. DracoDecoderModule(config_1);
  62503. });
  62504. });
  62505. }
  62506. return DracoCompression._DecoderModulePromise;
  62507. };
  62508. DracoCompression._LoadScriptAsync = function (url) {
  62509. return new Promise(function (resolve, reject) {
  62510. BABYLON.Tools.LoadScript(url, function () {
  62511. resolve();
  62512. }, function (message) {
  62513. reject(new Error(message));
  62514. });
  62515. });
  62516. };
  62517. DracoCompression._LoadFileAsync = function (url) {
  62518. return new Promise(function (resolve, reject) {
  62519. BABYLON.Tools.LoadFile(url, function (data) {
  62520. resolve(data);
  62521. }, undefined, undefined, true, function (request, exception) {
  62522. reject(exception);
  62523. });
  62524. });
  62525. };
  62526. /**
  62527. * The configuration. Defaults to the following urls:
  62528. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62529. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62530. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62531. */
  62532. DracoCompression.Configuration = {
  62533. decoder: {
  62534. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62535. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62536. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62537. }
  62538. };
  62539. return DracoCompression;
  62540. }());
  62541. BABYLON.DracoCompression = DracoCompression;
  62542. })(BABYLON || (BABYLON = {}));
  62543. //# sourceMappingURL=babylon.dracoCompression.js.map
  62544. var BABYLON;
  62545. (function (BABYLON) {
  62546. var AudioEngine = /** @class */ (function () {
  62547. function AudioEngine() {
  62548. this._audioContext = null;
  62549. this._audioContextInitialized = false;
  62550. this.canUseWebAudio = false;
  62551. this.WarnedWebAudioUnsupported = false;
  62552. this.unlocked = false;
  62553. this.isMP3supported = false;
  62554. this.isOGGsupported = false;
  62555. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62556. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62557. this.canUseWebAudio = true;
  62558. }
  62559. var audioElem = document.createElement('audio');
  62560. try {
  62561. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62562. this.isMP3supported = true;
  62563. }
  62564. }
  62565. catch (e) {
  62566. // protect error during capability check.
  62567. }
  62568. try {
  62569. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62570. this.isOGGsupported = true;
  62571. }
  62572. }
  62573. catch (e) {
  62574. // protect error during capability check.
  62575. }
  62576. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62577. this._unlockiOSaudio();
  62578. }
  62579. else {
  62580. this.unlocked = true;
  62581. }
  62582. }
  62583. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62584. get: function () {
  62585. if (!this._audioContextInitialized) {
  62586. this._initializeAudioContext();
  62587. }
  62588. return this._audioContext;
  62589. },
  62590. enumerable: true,
  62591. configurable: true
  62592. });
  62593. AudioEngine.prototype._unlockiOSaudio = function () {
  62594. var _this = this;
  62595. var unlockaudio = function () {
  62596. if (!_this.audioContext) {
  62597. return;
  62598. }
  62599. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62600. var source = _this.audioContext.createBufferSource();
  62601. source.buffer = buffer;
  62602. source.connect(_this.audioContext.destination);
  62603. source.start(0);
  62604. setTimeout(function () {
  62605. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62606. _this.unlocked = true;
  62607. window.removeEventListener('touchend', unlockaudio, false);
  62608. if (_this.onAudioUnlocked) {
  62609. _this.onAudioUnlocked();
  62610. }
  62611. }
  62612. }, 0);
  62613. };
  62614. window.addEventListener('touchend', unlockaudio, false);
  62615. };
  62616. AudioEngine.prototype._initializeAudioContext = function () {
  62617. try {
  62618. if (this.canUseWebAudio) {
  62619. this._audioContext = new AudioContext();
  62620. // create a global volume gain node
  62621. this.masterGain = this._audioContext.createGain();
  62622. this.masterGain.gain.value = 1;
  62623. this.masterGain.connect(this._audioContext.destination);
  62624. this._audioContextInitialized = true;
  62625. }
  62626. }
  62627. catch (e) {
  62628. this.canUseWebAudio = false;
  62629. BABYLON.Tools.Error("Web Audio: " + e.message);
  62630. }
  62631. };
  62632. AudioEngine.prototype.dispose = function () {
  62633. if (this.canUseWebAudio && this._audioContextInitialized) {
  62634. if (this._connectedAnalyser && this._audioContext) {
  62635. this._connectedAnalyser.stopDebugCanvas();
  62636. this._connectedAnalyser.dispose();
  62637. this.masterGain.disconnect();
  62638. this.masterGain.connect(this._audioContext.destination);
  62639. this._connectedAnalyser = null;
  62640. }
  62641. this.masterGain.gain.value = 1;
  62642. }
  62643. this.WarnedWebAudioUnsupported = false;
  62644. };
  62645. AudioEngine.prototype.getGlobalVolume = function () {
  62646. if (this.canUseWebAudio && this._audioContextInitialized) {
  62647. return this.masterGain.gain.value;
  62648. }
  62649. else {
  62650. return -1;
  62651. }
  62652. };
  62653. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62654. if (this.canUseWebAudio && this._audioContextInitialized) {
  62655. this.masterGain.gain.value = newVolume;
  62656. }
  62657. };
  62658. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62659. if (this._connectedAnalyser) {
  62660. this._connectedAnalyser.stopDebugCanvas();
  62661. }
  62662. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62663. this._connectedAnalyser = analyser;
  62664. this.masterGain.disconnect();
  62665. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62666. }
  62667. };
  62668. return AudioEngine;
  62669. }());
  62670. BABYLON.AudioEngine = AudioEngine;
  62671. })(BABYLON || (BABYLON = {}));
  62672. //# sourceMappingURL=babylon.audioEngine.js.map
  62673. var BABYLON;
  62674. (function (BABYLON) {
  62675. var Sound = /** @class */ (function () {
  62676. /**
  62677. * Create a sound and attach it to a scene
  62678. * @param name Name of your sound
  62679. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62680. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62681. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62682. */
  62683. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62684. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62685. var _this = this;
  62686. this.autoplay = false;
  62687. this.loop = false;
  62688. this.useCustomAttenuation = false;
  62689. this.spatialSound = false;
  62690. this.refDistance = 1;
  62691. this.rolloffFactor = 1;
  62692. this.maxDistance = 100;
  62693. this.distanceModel = "linear";
  62694. this._panningModel = "equalpower";
  62695. this._playbackRate = 1;
  62696. this._streaming = false;
  62697. this._startTime = 0;
  62698. this._startOffset = 0;
  62699. this._position = BABYLON.Vector3.Zero();
  62700. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62701. this._volume = 1;
  62702. this._isReadyToPlay = false;
  62703. this.isPlaying = false;
  62704. this.isPaused = false;
  62705. this._isDirectional = false;
  62706. // Used if you'd like to create a directional sound.
  62707. // If not set, the sound will be omnidirectional
  62708. this._coneInnerAngle = 360;
  62709. this._coneOuterAngle = 360;
  62710. this._coneOuterGain = 0;
  62711. this._isOutputConnected = false;
  62712. this._urlType = "Unknown";
  62713. this.name = name;
  62714. this._scene = scene;
  62715. this._readyToPlayCallback = readyToPlayCallback;
  62716. // Default custom attenuation function is a linear attenuation
  62717. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62718. if (currentDistance < maxDistance) {
  62719. return currentVolume * (1 - currentDistance / maxDistance);
  62720. }
  62721. else {
  62722. return 0;
  62723. }
  62724. };
  62725. if (options) {
  62726. this.autoplay = options.autoplay || false;
  62727. this.loop = options.loop || false;
  62728. // if volume === 0, we need another way to check this option
  62729. if (options.volume !== undefined) {
  62730. this._volume = options.volume;
  62731. }
  62732. this.spatialSound = options.spatialSound || false;
  62733. this.maxDistance = options.maxDistance || 100;
  62734. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62735. this.rolloffFactor = options.rolloffFactor || 1;
  62736. this.refDistance = options.refDistance || 1;
  62737. this.distanceModel = options.distanceModel || "linear";
  62738. this._playbackRate = options.playbackRate || 1;
  62739. this._streaming = options.streaming || false;
  62740. }
  62741. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62742. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62743. this._soundGain.gain.value = this._volume;
  62744. this._inputAudioNode = this._soundGain;
  62745. this._ouputAudioNode = this._soundGain;
  62746. if (this.spatialSound) {
  62747. this._createSpatialParameters();
  62748. }
  62749. this._scene.mainSoundTrack.AddSound(this);
  62750. var validParameter = true;
  62751. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62752. if (urlOrArrayBuffer) {
  62753. try {
  62754. if (typeof (urlOrArrayBuffer) === "string")
  62755. this._urlType = "String";
  62756. if (Array.isArray(urlOrArrayBuffer))
  62757. this._urlType = "Array";
  62758. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62759. this._urlType = "ArrayBuffer";
  62760. var urls = [];
  62761. var codecSupportedFound = false;
  62762. switch (this._urlType) {
  62763. case "ArrayBuffer":
  62764. if (urlOrArrayBuffer.byteLength > 0) {
  62765. codecSupportedFound = true;
  62766. this._soundLoaded(urlOrArrayBuffer);
  62767. }
  62768. break;
  62769. case "String":
  62770. urls.push(urlOrArrayBuffer);
  62771. case "Array":
  62772. if (urls.length === 0)
  62773. urls = urlOrArrayBuffer;
  62774. // If we found a supported format, we load it immediately and stop the loop
  62775. for (var i = 0; i < urls.length; i++) {
  62776. var url = urls[i];
  62777. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62778. codecSupportedFound = true;
  62779. }
  62780. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62781. codecSupportedFound = true;
  62782. }
  62783. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62784. codecSupportedFound = true;
  62785. }
  62786. if (url.indexOf("blob:") !== -1) {
  62787. codecSupportedFound = true;
  62788. }
  62789. if (codecSupportedFound) {
  62790. // Loading sound using XHR2
  62791. if (!this._streaming) {
  62792. this._scene._loadFile(url, function (data) {
  62793. _this._soundLoaded(data);
  62794. }, undefined, true, true, function (exception) {
  62795. if (exception) {
  62796. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62797. }
  62798. BABYLON.Tools.Error("Sound creation aborted.");
  62799. _this._scene.mainSoundTrack.RemoveSound(_this);
  62800. });
  62801. }
  62802. // Streaming sound using HTML5 Audio tag
  62803. else {
  62804. this._htmlAudioElement = new Audio(url);
  62805. this._htmlAudioElement.controls = false;
  62806. this._htmlAudioElement.loop = this.loop;
  62807. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62808. this._htmlAudioElement.preload = "auto";
  62809. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62810. _this._isReadyToPlay = true;
  62811. if (_this.autoplay) {
  62812. _this.play();
  62813. }
  62814. if (_this._readyToPlayCallback) {
  62815. _this._readyToPlayCallback();
  62816. }
  62817. });
  62818. document.body.appendChild(this._htmlAudioElement);
  62819. }
  62820. break;
  62821. }
  62822. }
  62823. break;
  62824. default:
  62825. validParameter = false;
  62826. break;
  62827. }
  62828. if (!validParameter) {
  62829. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62830. }
  62831. else {
  62832. if (!codecSupportedFound) {
  62833. this._isReadyToPlay = true;
  62834. // Simulating a ready to play event to avoid breaking code path
  62835. if (this._readyToPlayCallback) {
  62836. window.setTimeout(function () {
  62837. if (_this._readyToPlayCallback) {
  62838. _this._readyToPlayCallback();
  62839. }
  62840. }, 1000);
  62841. }
  62842. }
  62843. }
  62844. }
  62845. catch (ex) {
  62846. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62847. this._scene.mainSoundTrack.RemoveSound(this);
  62848. }
  62849. }
  62850. }
  62851. else {
  62852. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62853. this._scene.mainSoundTrack.AddSound(this);
  62854. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62855. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62856. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62857. }
  62858. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62859. if (this._readyToPlayCallback) {
  62860. window.setTimeout(function () {
  62861. if (_this._readyToPlayCallback) {
  62862. _this._readyToPlayCallback();
  62863. }
  62864. }, 1000);
  62865. }
  62866. }
  62867. }
  62868. Sound.prototype.dispose = function () {
  62869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62870. if (this.isPlaying) {
  62871. this.stop();
  62872. }
  62873. this._isReadyToPlay = false;
  62874. if (this.soundTrackId === -1) {
  62875. this._scene.mainSoundTrack.RemoveSound(this);
  62876. }
  62877. else {
  62878. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62879. }
  62880. if (this._soundGain) {
  62881. this._soundGain.disconnect();
  62882. this._soundGain = null;
  62883. }
  62884. if (this._soundPanner) {
  62885. this._soundPanner.disconnect();
  62886. this._soundPanner = null;
  62887. }
  62888. if (this._soundSource) {
  62889. this._soundSource.disconnect();
  62890. this._soundSource = null;
  62891. }
  62892. this._audioBuffer = null;
  62893. if (this._htmlAudioElement) {
  62894. this._htmlAudioElement.pause();
  62895. this._htmlAudioElement.src = "";
  62896. document.body.removeChild(this._htmlAudioElement);
  62897. }
  62898. if (this._connectedMesh && this._registerFunc) {
  62899. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62900. this._connectedMesh = null;
  62901. }
  62902. }
  62903. };
  62904. Sound.prototype.isReady = function () {
  62905. return this._isReadyToPlay;
  62906. };
  62907. Sound.prototype._soundLoaded = function (audioData) {
  62908. var _this = this;
  62909. if (!BABYLON.Engine.audioEngine.audioContext) {
  62910. return;
  62911. }
  62912. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62913. _this._audioBuffer = buffer;
  62914. _this._isReadyToPlay = true;
  62915. if (_this.autoplay) {
  62916. _this.play();
  62917. }
  62918. if (_this._readyToPlayCallback) {
  62919. _this._readyToPlayCallback();
  62920. }
  62921. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62922. };
  62923. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62924. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62925. this._audioBuffer = audioBuffer;
  62926. this._isReadyToPlay = true;
  62927. }
  62928. };
  62929. Sound.prototype.updateOptions = function (options) {
  62930. if (options) {
  62931. this.loop = options.loop || this.loop;
  62932. this.maxDistance = options.maxDistance || this.maxDistance;
  62933. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62934. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62935. this.refDistance = options.refDistance || this.refDistance;
  62936. this.distanceModel = options.distanceModel || this.distanceModel;
  62937. this._playbackRate = options.playbackRate || this._playbackRate;
  62938. this._updateSpatialParameters();
  62939. if (this.isPlaying) {
  62940. if (this._streaming) {
  62941. this._htmlAudioElement.playbackRate = this._playbackRate;
  62942. }
  62943. else {
  62944. if (this._soundSource) {
  62945. this._soundSource.playbackRate.value = this._playbackRate;
  62946. }
  62947. }
  62948. }
  62949. }
  62950. };
  62951. Sound.prototype._createSpatialParameters = function () {
  62952. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62953. if (this._scene.headphone) {
  62954. this._panningModel = "HRTF";
  62955. }
  62956. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62957. this._updateSpatialParameters();
  62958. this._soundPanner.connect(this._ouputAudioNode);
  62959. this._inputAudioNode = this._soundPanner;
  62960. }
  62961. };
  62962. Sound.prototype._updateSpatialParameters = function () {
  62963. if (this.spatialSound && this._soundPanner) {
  62964. if (this.useCustomAttenuation) {
  62965. // Tricks to disable in a way embedded Web Audio attenuation
  62966. this._soundPanner.distanceModel = "linear";
  62967. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62968. this._soundPanner.refDistance = 1;
  62969. this._soundPanner.rolloffFactor = 1;
  62970. this._soundPanner.panningModel = this._panningModel;
  62971. }
  62972. else {
  62973. this._soundPanner.distanceModel = this.distanceModel;
  62974. this._soundPanner.maxDistance = this.maxDistance;
  62975. this._soundPanner.refDistance = this.refDistance;
  62976. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62977. this._soundPanner.panningModel = this._panningModel;
  62978. }
  62979. }
  62980. };
  62981. Sound.prototype.switchPanningModelToHRTF = function () {
  62982. this._panningModel = "HRTF";
  62983. this._switchPanningModel();
  62984. };
  62985. Sound.prototype.switchPanningModelToEqualPower = function () {
  62986. this._panningModel = "equalpower";
  62987. this._switchPanningModel();
  62988. };
  62989. Sound.prototype._switchPanningModel = function () {
  62990. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62991. this._soundPanner.panningModel = this._panningModel;
  62992. }
  62993. };
  62994. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62996. if (this._isOutputConnected) {
  62997. this._ouputAudioNode.disconnect();
  62998. }
  62999. this._ouputAudioNode.connect(soundTrackAudioNode);
  63000. this._isOutputConnected = true;
  63001. }
  63002. };
  63003. /**
  63004. * Transform this sound into a directional source
  63005. * @param coneInnerAngle Size of the inner cone in degree
  63006. * @param coneOuterAngle Size of the outer cone in degree
  63007. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63008. */
  63009. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63010. if (coneOuterAngle < coneInnerAngle) {
  63011. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63012. return;
  63013. }
  63014. this._coneInnerAngle = coneInnerAngle;
  63015. this._coneOuterAngle = coneOuterAngle;
  63016. this._coneOuterGain = coneOuterGain;
  63017. this._isDirectional = true;
  63018. if (this.isPlaying && this.loop) {
  63019. this.stop();
  63020. this.play();
  63021. }
  63022. };
  63023. Sound.prototype.setPosition = function (newPosition) {
  63024. this._position = newPosition;
  63025. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63026. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63027. }
  63028. };
  63029. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63030. this._localDirection = newLocalDirection;
  63031. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63032. this._updateDirection();
  63033. }
  63034. };
  63035. Sound.prototype._updateDirection = function () {
  63036. if (!this._connectedMesh || !this._soundPanner) {
  63037. return;
  63038. }
  63039. var mat = this._connectedMesh.getWorldMatrix();
  63040. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63041. direction.normalize();
  63042. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63043. };
  63044. Sound.prototype.updateDistanceFromListener = function () {
  63045. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63046. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63047. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63048. }
  63049. };
  63050. Sound.prototype.setAttenuationFunction = function (callback) {
  63051. this._customAttenuationFunction = callback;
  63052. };
  63053. /**
  63054. * Play the sound
  63055. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63056. * @param offset (optional) Start the sound setting it at a specific time
  63057. */
  63058. Sound.prototype.play = function (time, offset) {
  63059. var _this = this;
  63060. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63061. try {
  63062. if (this._startOffset < 0) {
  63063. time = -this._startOffset;
  63064. this._startOffset = 0;
  63065. }
  63066. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63067. if (!this._soundSource || !this._streamingSource) {
  63068. if (this.spatialSound && this._soundPanner) {
  63069. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63070. if (this._isDirectional) {
  63071. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63072. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63073. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63074. if (this._connectedMesh) {
  63075. this._updateDirection();
  63076. }
  63077. else {
  63078. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63079. }
  63080. }
  63081. }
  63082. }
  63083. if (this._streaming) {
  63084. if (!this._streamingSource) {
  63085. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63086. this._htmlAudioElement.onended = function () { _this._onended(); };
  63087. this._htmlAudioElement.playbackRate = this._playbackRate;
  63088. }
  63089. this._streamingSource.disconnect();
  63090. this._streamingSource.connect(this._inputAudioNode);
  63091. this._htmlAudioElement.play();
  63092. }
  63093. else {
  63094. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63095. this._soundSource.buffer = this._audioBuffer;
  63096. this._soundSource.connect(this._inputAudioNode);
  63097. this._soundSource.loop = this.loop;
  63098. this._soundSource.playbackRate.value = this._playbackRate;
  63099. this._soundSource.onended = function () { _this._onended(); };
  63100. if (this._soundSource.buffer) {
  63101. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63102. }
  63103. }
  63104. this._startTime = startTime;
  63105. this.isPlaying = true;
  63106. this.isPaused = false;
  63107. }
  63108. catch (ex) {
  63109. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63110. }
  63111. }
  63112. };
  63113. Sound.prototype._onended = function () {
  63114. this.isPlaying = false;
  63115. if (this.onended) {
  63116. this.onended();
  63117. }
  63118. };
  63119. /**
  63120. * Stop the sound
  63121. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63122. */
  63123. Sound.prototype.stop = function (time) {
  63124. if (this.isPlaying) {
  63125. if (this._streaming) {
  63126. this._htmlAudioElement.pause();
  63127. // Test needed for Firefox or it will generate an Invalid State Error
  63128. if (this._htmlAudioElement.currentTime > 0) {
  63129. this._htmlAudioElement.currentTime = 0;
  63130. }
  63131. }
  63132. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63133. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63134. this._soundSource.stop(stopTime);
  63135. this._soundSource.onended = function () { };
  63136. if (!this.isPaused) {
  63137. this._startOffset = 0;
  63138. }
  63139. }
  63140. this.isPlaying = false;
  63141. }
  63142. };
  63143. Sound.prototype.pause = function () {
  63144. if (this.isPlaying) {
  63145. this.isPaused = true;
  63146. if (this._streaming) {
  63147. this._htmlAudioElement.pause();
  63148. }
  63149. else if (BABYLON.Engine.audioEngine.audioContext) {
  63150. this.stop(0);
  63151. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63152. }
  63153. }
  63154. };
  63155. Sound.prototype.setVolume = function (newVolume, time) {
  63156. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63157. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63158. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63159. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63160. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63161. }
  63162. else {
  63163. this._soundGain.gain.value = newVolume;
  63164. }
  63165. }
  63166. this._volume = newVolume;
  63167. };
  63168. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63169. this._playbackRate = newPlaybackRate;
  63170. if (this.isPlaying) {
  63171. if (this._streaming) {
  63172. this._htmlAudioElement.playbackRate = this._playbackRate;
  63173. }
  63174. else if (this._soundSource) {
  63175. this._soundSource.playbackRate.value = this._playbackRate;
  63176. }
  63177. }
  63178. };
  63179. Sound.prototype.getVolume = function () {
  63180. return this._volume;
  63181. };
  63182. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63183. var _this = this;
  63184. if (this._connectedMesh && this._registerFunc) {
  63185. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63186. this._registerFunc = null;
  63187. }
  63188. this._connectedMesh = meshToConnectTo;
  63189. if (!this.spatialSound) {
  63190. this.spatialSound = true;
  63191. this._createSpatialParameters();
  63192. if (this.isPlaying && this.loop) {
  63193. this.stop();
  63194. this.play();
  63195. }
  63196. }
  63197. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63198. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63199. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63200. };
  63201. Sound.prototype.detachFromMesh = function () {
  63202. if (this._connectedMesh && this._registerFunc) {
  63203. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63204. this._registerFunc = null;
  63205. this._connectedMesh = null;
  63206. }
  63207. };
  63208. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63209. if (!node.getBoundingInfo) {
  63210. return;
  63211. }
  63212. var mesh = node;
  63213. var boundingInfo = mesh.getBoundingInfo();
  63214. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63215. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63216. this._updateDirection();
  63217. }
  63218. };
  63219. Sound.prototype.clone = function () {
  63220. var _this = this;
  63221. if (!this._streaming) {
  63222. var setBufferAndRun = function () {
  63223. if (_this._isReadyToPlay) {
  63224. clonedSound._audioBuffer = _this.getAudioBuffer();
  63225. clonedSound._isReadyToPlay = true;
  63226. if (clonedSound.autoplay) {
  63227. clonedSound.play();
  63228. }
  63229. }
  63230. else {
  63231. window.setTimeout(setBufferAndRun, 300);
  63232. }
  63233. };
  63234. var currentOptions = {
  63235. autoplay: this.autoplay, loop: this.loop,
  63236. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63237. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63238. refDistance: this.refDistance, distanceModel: this.distanceModel
  63239. };
  63240. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63241. if (this.useCustomAttenuation) {
  63242. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63243. }
  63244. clonedSound.setPosition(this._position);
  63245. clonedSound.setPlaybackRate(this._playbackRate);
  63246. setBufferAndRun();
  63247. return clonedSound;
  63248. }
  63249. // Can't clone a streaming sound
  63250. else {
  63251. return null;
  63252. }
  63253. };
  63254. Sound.prototype.getAudioBuffer = function () {
  63255. return this._audioBuffer;
  63256. };
  63257. Sound.prototype.serialize = function () {
  63258. var serializationObject = {
  63259. name: this.name,
  63260. url: this.name,
  63261. autoplay: this.autoplay,
  63262. loop: this.loop,
  63263. volume: this._volume,
  63264. spatialSound: this.spatialSound,
  63265. maxDistance: this.maxDistance,
  63266. rolloffFactor: this.rolloffFactor,
  63267. refDistance: this.refDistance,
  63268. distanceModel: this.distanceModel,
  63269. playbackRate: this._playbackRate,
  63270. panningModel: this._panningModel,
  63271. soundTrackId: this.soundTrackId
  63272. };
  63273. if (this.spatialSound) {
  63274. if (this._connectedMesh)
  63275. serializationObject.connectedMeshId = this._connectedMesh.id;
  63276. serializationObject.position = this._position.asArray();
  63277. serializationObject.refDistance = this.refDistance;
  63278. serializationObject.distanceModel = this.distanceModel;
  63279. serializationObject.isDirectional = this._isDirectional;
  63280. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63281. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63282. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63283. serializationObject.coneOuterGain = this._coneOuterGain;
  63284. }
  63285. return serializationObject;
  63286. };
  63287. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63288. var soundName = parsedSound.name;
  63289. var soundUrl;
  63290. if (parsedSound.url) {
  63291. soundUrl = rootUrl + parsedSound.url;
  63292. }
  63293. else {
  63294. soundUrl = rootUrl + soundName;
  63295. }
  63296. var options = {
  63297. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63298. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63299. rolloffFactor: parsedSound.rolloffFactor,
  63300. refDistance: parsedSound.refDistance,
  63301. distanceModel: parsedSound.distanceModel,
  63302. playbackRate: parsedSound.playbackRate
  63303. };
  63304. var newSound;
  63305. if (!sourceSound) {
  63306. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63307. scene._addPendingData(newSound);
  63308. }
  63309. else {
  63310. var setBufferAndRun = function () {
  63311. if (sourceSound._isReadyToPlay) {
  63312. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63313. newSound._isReadyToPlay = true;
  63314. if (newSound.autoplay) {
  63315. newSound.play();
  63316. }
  63317. }
  63318. else {
  63319. window.setTimeout(setBufferAndRun, 300);
  63320. }
  63321. };
  63322. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63323. setBufferAndRun();
  63324. }
  63325. if (parsedSound.position) {
  63326. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63327. newSound.setPosition(soundPosition);
  63328. }
  63329. if (parsedSound.isDirectional) {
  63330. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63331. if (parsedSound.localDirectionToMesh) {
  63332. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63333. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63334. }
  63335. }
  63336. if (parsedSound.connectedMeshId) {
  63337. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63338. if (connectedMesh) {
  63339. newSound.attachToMesh(connectedMesh);
  63340. }
  63341. }
  63342. return newSound;
  63343. };
  63344. return Sound;
  63345. }());
  63346. BABYLON.Sound = Sound;
  63347. })(BABYLON || (BABYLON = {}));
  63348. //# sourceMappingURL=babylon.sound.js.map
  63349. var BABYLON;
  63350. (function (BABYLON) {
  63351. var SoundTrack = /** @class */ (function () {
  63352. function SoundTrack(scene, options) {
  63353. this.id = -1;
  63354. this._isMainTrack = false;
  63355. this._isInitialized = false;
  63356. this._scene = scene;
  63357. this.soundCollection = new Array();
  63358. this._options = options;
  63359. if (!this._isMainTrack) {
  63360. this._scene.soundTracks.push(this);
  63361. this.id = this._scene.soundTracks.length - 1;
  63362. }
  63363. }
  63364. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63365. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63366. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63367. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63368. if (this._options) {
  63369. if (this._options.volume) {
  63370. this._outputAudioNode.gain.value = this._options.volume;
  63371. }
  63372. if (this._options.mainTrack) {
  63373. this._isMainTrack = this._options.mainTrack;
  63374. }
  63375. }
  63376. this._isInitialized = true;
  63377. }
  63378. };
  63379. SoundTrack.prototype.dispose = function () {
  63380. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63381. if (this._connectedAnalyser) {
  63382. this._connectedAnalyser.stopDebugCanvas();
  63383. }
  63384. while (this.soundCollection.length) {
  63385. this.soundCollection[0].dispose();
  63386. }
  63387. if (this._outputAudioNode) {
  63388. this._outputAudioNode.disconnect();
  63389. }
  63390. this._outputAudioNode = null;
  63391. }
  63392. };
  63393. SoundTrack.prototype.AddSound = function (sound) {
  63394. if (!this._isInitialized) {
  63395. this._initializeSoundTrackAudioGraph();
  63396. }
  63397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63398. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63399. }
  63400. if (sound.soundTrackId) {
  63401. if (sound.soundTrackId === -1) {
  63402. this._scene.mainSoundTrack.RemoveSound(sound);
  63403. }
  63404. else {
  63405. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63406. }
  63407. }
  63408. this.soundCollection.push(sound);
  63409. sound.soundTrackId = this.id;
  63410. };
  63411. SoundTrack.prototype.RemoveSound = function (sound) {
  63412. var index = this.soundCollection.indexOf(sound);
  63413. if (index !== -1) {
  63414. this.soundCollection.splice(index, 1);
  63415. }
  63416. };
  63417. SoundTrack.prototype.setVolume = function (newVolume) {
  63418. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63419. this._outputAudioNode.gain.value = newVolume;
  63420. }
  63421. };
  63422. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63424. for (var i = 0; i < this.soundCollection.length; i++) {
  63425. this.soundCollection[i].switchPanningModelToHRTF();
  63426. }
  63427. }
  63428. };
  63429. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63430. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63431. for (var i = 0; i < this.soundCollection.length; i++) {
  63432. this.soundCollection[i].switchPanningModelToEqualPower();
  63433. }
  63434. }
  63435. };
  63436. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63437. if (this._connectedAnalyser) {
  63438. this._connectedAnalyser.stopDebugCanvas();
  63439. }
  63440. this._connectedAnalyser = analyser;
  63441. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63442. this._outputAudioNode.disconnect();
  63443. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63444. }
  63445. };
  63446. return SoundTrack;
  63447. }());
  63448. BABYLON.SoundTrack = SoundTrack;
  63449. })(BABYLON || (BABYLON = {}));
  63450. //# sourceMappingURL=babylon.soundtrack.js.map
  63451. var BABYLON;
  63452. (function (BABYLON) {
  63453. /**
  63454. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63455. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63456. */
  63457. var Analyser = /** @class */ (function () {
  63458. /**
  63459. * Creates a new analyser
  63460. * @param scene defines hosting scene
  63461. */
  63462. function Analyser(scene) {
  63463. /**
  63464. * Gets or sets the smoothing
  63465. * @ignorenaming
  63466. */
  63467. this.SMOOTHING = 0.75;
  63468. /**
  63469. * Gets or sets the FFT table size
  63470. * @ignorenaming
  63471. */
  63472. this.FFT_SIZE = 512;
  63473. /**
  63474. * Gets or sets the bar graph amplitude
  63475. * @ignorenaming
  63476. */
  63477. this.BARGRAPHAMPLITUDE = 256;
  63478. /**
  63479. * Gets or sets the position of the debug canvas
  63480. * @ignorenaming
  63481. */
  63482. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63483. /**
  63484. * Gets or sets the debug canvas size
  63485. * @ignorenaming
  63486. */
  63487. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63488. this._scene = scene;
  63489. this._audioEngine = BABYLON.Engine.audioEngine;
  63490. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63491. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63492. this._webAudioAnalyser.minDecibels = -140;
  63493. this._webAudioAnalyser.maxDecibels = 0;
  63494. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63495. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63496. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63497. }
  63498. }
  63499. /**
  63500. * Get the number of data values you will have to play with for the visualization
  63501. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63502. * @returns a number
  63503. */
  63504. Analyser.prototype.getFrequencyBinCount = function () {
  63505. if (this._audioEngine.canUseWebAudio) {
  63506. return this._webAudioAnalyser.frequencyBinCount;
  63507. }
  63508. else {
  63509. return 0;
  63510. }
  63511. };
  63512. /**
  63513. * Gets the current frequency data as a byte array
  63514. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63515. * @returns a Uint8Array
  63516. */
  63517. Analyser.prototype.getByteFrequencyData = function () {
  63518. if (this._audioEngine.canUseWebAudio) {
  63519. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63520. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63521. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63522. }
  63523. return this._byteFreqs;
  63524. };
  63525. /**
  63526. * Gets the current waveform as a byte array
  63527. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63528. * @returns a Uint8Array
  63529. */
  63530. Analyser.prototype.getByteTimeDomainData = function () {
  63531. if (this._audioEngine.canUseWebAudio) {
  63532. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63533. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63534. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63535. }
  63536. return this._byteTime;
  63537. };
  63538. /**
  63539. * Gets the current frequency data as a float array
  63540. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63541. * @returns a Float32Array
  63542. */
  63543. Analyser.prototype.getFloatFrequencyData = function () {
  63544. if (this._audioEngine.canUseWebAudio) {
  63545. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63546. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63547. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63548. }
  63549. return this._floatFreqs;
  63550. };
  63551. /**
  63552. * Renders the debug canvas
  63553. */
  63554. Analyser.prototype.drawDebugCanvas = function () {
  63555. var _this = this;
  63556. if (this._audioEngine.canUseWebAudio) {
  63557. if (!this._debugCanvas) {
  63558. this._debugCanvas = document.createElement("canvas");
  63559. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63560. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63561. this._debugCanvas.style.position = "absolute";
  63562. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63563. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63564. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63565. document.body.appendChild(this._debugCanvas);
  63566. this._registerFunc = function () {
  63567. _this.drawDebugCanvas();
  63568. };
  63569. this._scene.registerBeforeRender(this._registerFunc);
  63570. }
  63571. if (this._registerFunc && this._debugCanvasContext) {
  63572. var workingArray = this.getByteFrequencyData();
  63573. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63574. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63575. // Draw the frequency domain chart.
  63576. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63577. var value = workingArray[i];
  63578. var percent = value / this.BARGRAPHAMPLITUDE;
  63579. var height = this.DEBUGCANVASSIZE.height * percent;
  63580. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63581. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63582. var hue = i / this.getFrequencyBinCount() * 360;
  63583. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63584. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63585. }
  63586. }
  63587. }
  63588. };
  63589. /**
  63590. * Stops rendering the debug canvas and removes it
  63591. */
  63592. Analyser.prototype.stopDebugCanvas = function () {
  63593. if (this._debugCanvas) {
  63594. if (this._registerFunc) {
  63595. this._scene.unregisterBeforeRender(this._registerFunc);
  63596. this._registerFunc = null;
  63597. }
  63598. document.body.removeChild(this._debugCanvas);
  63599. this._debugCanvas = null;
  63600. this._debugCanvasContext = null;
  63601. }
  63602. };
  63603. /**
  63604. * Connects two audio nodes
  63605. * @param inputAudioNode defines first node to connect
  63606. * @param outputAudioNode defines second node to connect
  63607. */
  63608. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63609. if (this._audioEngine.canUseWebAudio) {
  63610. inputAudioNode.connect(this._webAudioAnalyser);
  63611. this._webAudioAnalyser.connect(outputAudioNode);
  63612. }
  63613. };
  63614. /**
  63615. * Releases all associated resources
  63616. */
  63617. Analyser.prototype.dispose = function () {
  63618. if (this._audioEngine.canUseWebAudio) {
  63619. this._webAudioAnalyser.disconnect();
  63620. }
  63621. };
  63622. return Analyser;
  63623. }());
  63624. BABYLON.Analyser = Analyser;
  63625. })(BABYLON || (BABYLON = {}));
  63626. //# sourceMappingURL=babylon.analyser.js.map
  63627. var BABYLON;
  63628. (function (BABYLON) {
  63629. var CubeTexture = /** @class */ (function (_super) {
  63630. __extends(CubeTexture, _super);
  63631. /**
  63632. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63633. * as prefiltered data.
  63634. * @param rootUrl defines the url of the texture or the root name of the six images
  63635. * @param scene defines the scene the texture is attached to
  63636. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63637. * @param noMipmap defines if mipmaps should be created or not
  63638. * @param files defines the six files to load for the different faces
  63639. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63640. * @param onError defines a callback triggered in case of error during load
  63641. * @param format defines the internal format to use for the texture once loaded
  63642. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63643. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63644. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63645. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63646. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63647. * @return the cube texture
  63648. */
  63649. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63650. if (extensions === void 0) { extensions = null; }
  63651. if (noMipmap === void 0) { noMipmap = false; }
  63652. if (files === void 0) { files = null; }
  63653. if (onLoad === void 0) { onLoad = null; }
  63654. if (onError === void 0) { onError = null; }
  63655. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63656. if (prefiltered === void 0) { prefiltered = false; }
  63657. if (forcedExtension === void 0) { forcedExtension = null; }
  63658. if (createPolynomials === void 0) { createPolynomials = false; }
  63659. if (lodScale === void 0) { lodScale = 0.8; }
  63660. if (lodOffset === void 0) { lodOffset = 0; }
  63661. var _this = _super.call(this, scene) || this;
  63662. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63663. /**
  63664. * Gets or sets the center of the bounding box associated with the cube texture
  63665. * It must define where the camera used to render the texture was set
  63666. */
  63667. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63668. _this._rotationY = 0;
  63669. /** @hidden */
  63670. _this._prefiltered = false;
  63671. _this.name = rootUrl;
  63672. _this.url = rootUrl;
  63673. _this._noMipmap = noMipmap;
  63674. _this.hasAlpha = false;
  63675. _this._format = format;
  63676. _this.isCube = true;
  63677. _this._textureMatrix = BABYLON.Matrix.Identity();
  63678. _this._createPolynomials = createPolynomials;
  63679. if (!rootUrl && !files) {
  63680. return _this;
  63681. }
  63682. var lastDot = rootUrl.lastIndexOf(".");
  63683. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63684. var isDDS = (extension === ".dds");
  63685. var isEnv = (extension === ".env");
  63686. if (isEnv) {
  63687. _this.gammaSpace = false;
  63688. _this._prefiltered = false;
  63689. }
  63690. else {
  63691. _this._prefiltered = prefiltered;
  63692. if (prefiltered) {
  63693. _this.gammaSpace = false;
  63694. }
  63695. }
  63696. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63697. if (!files) {
  63698. if (!isEnv && !isDDS && !extensions) {
  63699. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63700. }
  63701. files = [];
  63702. if (extensions) {
  63703. for (var index = 0; index < extensions.length; index++) {
  63704. files.push(rootUrl + extensions[index]);
  63705. }
  63706. }
  63707. }
  63708. _this._files = files;
  63709. if (!_this._texture) {
  63710. if (!scene.useDelayedTextureLoading) {
  63711. if (prefiltered) {
  63712. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63713. }
  63714. else {
  63715. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63716. }
  63717. }
  63718. else {
  63719. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63720. }
  63721. }
  63722. else if (onLoad) {
  63723. if (_this._texture.isReady) {
  63724. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63725. }
  63726. else {
  63727. _this._texture.onLoadedObservable.add(onLoad);
  63728. }
  63729. }
  63730. return _this;
  63731. }
  63732. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63733. get: function () {
  63734. return this._boundingBoxSize;
  63735. },
  63736. /**
  63737. * Gets or sets the size of the bounding box associated with the cube texture
  63738. * When defined, the cubemap will switch to local mode
  63739. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63740. * @example https://www.babylonjs-playground.com/#RNASML
  63741. */
  63742. set: function (value) {
  63743. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63744. return;
  63745. }
  63746. this._boundingBoxSize = value;
  63747. var scene = this.getScene();
  63748. if (scene) {
  63749. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63750. }
  63751. },
  63752. enumerable: true,
  63753. configurable: true
  63754. });
  63755. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63756. /**
  63757. * Gets texture matrix rotation angle around Y axis radians.
  63758. */
  63759. get: function () {
  63760. return this._rotationY;
  63761. },
  63762. /**
  63763. * Sets texture matrix rotation angle around Y axis in radians.
  63764. */
  63765. set: function (value) {
  63766. this._rotationY = value;
  63767. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63768. },
  63769. enumerable: true,
  63770. configurable: true
  63771. });
  63772. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63773. var rootUrlKey = "";
  63774. files.forEach(function (url) { return rootUrlKey += url; });
  63775. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63776. };
  63777. /**
  63778. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63779. * @param url defines the url of the prefiltered texture
  63780. * @param scene defines the scene the texture is attached to
  63781. * @param forcedExtension defines the extension of the file if different from the url
  63782. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63783. * @return the prefiltered texture
  63784. */
  63785. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63786. if (forcedExtension === void 0) { forcedExtension = null; }
  63787. if (createPolynomials === void 0) { createPolynomials = true; }
  63788. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63789. };
  63790. // Methods
  63791. CubeTexture.prototype.delayLoad = function () {
  63792. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63793. return;
  63794. }
  63795. var scene = this.getScene();
  63796. if (!scene) {
  63797. return;
  63798. }
  63799. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63800. this._texture = this._getFromCache(this.url, this._noMipmap);
  63801. if (!this._texture) {
  63802. if (this._prefiltered) {
  63803. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63804. }
  63805. else {
  63806. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63807. }
  63808. }
  63809. };
  63810. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63811. return this._textureMatrix;
  63812. };
  63813. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63814. this._textureMatrix = value;
  63815. };
  63816. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63817. var texture = BABYLON.SerializationHelper.Parse(function () {
  63818. var prefiltered = false;
  63819. if (parsedTexture.prefiltered) {
  63820. prefiltered = parsedTexture.prefiltered;
  63821. }
  63822. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63823. }, parsedTexture, scene);
  63824. // Local Cubemaps
  63825. if (parsedTexture.boundingBoxPosition) {
  63826. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63827. }
  63828. if (parsedTexture.boundingBoxSize) {
  63829. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63830. }
  63831. // Animations
  63832. if (parsedTexture.animations) {
  63833. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63834. var parsedAnimation = parsedTexture.animations[animationIndex];
  63835. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63836. }
  63837. }
  63838. return texture;
  63839. };
  63840. CubeTexture.prototype.clone = function () {
  63841. var _this = this;
  63842. return BABYLON.SerializationHelper.Clone(function () {
  63843. var scene = _this.getScene();
  63844. if (!scene) {
  63845. return _this;
  63846. }
  63847. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63848. }, this);
  63849. };
  63850. __decorate([
  63851. BABYLON.serialize("rotationY")
  63852. ], CubeTexture.prototype, "_rotationY", void 0);
  63853. return CubeTexture;
  63854. }(BABYLON.BaseTexture));
  63855. BABYLON.CubeTexture = CubeTexture;
  63856. })(BABYLON || (BABYLON = {}));
  63857. //# sourceMappingURL=babylon.cubeTexture.js.map
  63858. var BABYLON;
  63859. (function (BABYLON) {
  63860. var RenderTargetTexture = /** @class */ (function (_super) {
  63861. __extends(RenderTargetTexture, _super);
  63862. /**
  63863. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63864. * or used a shadow, depth texture...
  63865. * @param name The friendly name of the texture
  63866. * @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)
  63867. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63868. * @param generateMipMaps True if mip maps need to be generated after render.
  63869. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63870. * @param type The type of the buffer in the RTT (int, half float, float...)
  63871. * @param isCube True if a cube texture needs to be created
  63872. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63873. * @param generateDepthBuffer True to generate a depth buffer
  63874. * @param generateStencilBuffer True to generate a stencil buffer
  63875. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63876. */
  63877. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63878. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63879. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63880. if (isCube === void 0) { isCube = false; }
  63881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63882. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63883. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63884. if (isMulti === void 0) { isMulti = false; }
  63885. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63886. _this.isCube = isCube;
  63887. /**
  63888. * Use this list to define the list of mesh you want to render.
  63889. */
  63890. _this.renderList = new Array();
  63891. _this.renderParticles = true;
  63892. _this.renderSprites = false;
  63893. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63894. _this.ignoreCameraViewport = false;
  63895. // Events
  63896. /**
  63897. * An event triggered when the texture is unbind.
  63898. */
  63899. _this.onBeforeBindObservable = new BABYLON.Observable();
  63900. /**
  63901. * An event triggered when the texture is unbind.
  63902. */
  63903. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63904. /**
  63905. * An event triggered before rendering the texture
  63906. */
  63907. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63908. /**
  63909. * An event triggered after rendering the texture
  63910. */
  63911. _this.onAfterRenderObservable = new BABYLON.Observable();
  63912. /**
  63913. * An event triggered after the texture clear
  63914. */
  63915. _this.onClearObservable = new BABYLON.Observable();
  63916. _this._currentRefreshId = -1;
  63917. _this._refreshRate = 1;
  63918. _this._samples = 1;
  63919. /**
  63920. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63921. * It must define where the camera used to render the texture is set
  63922. */
  63923. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63924. scene = _this.getScene();
  63925. if (!scene) {
  63926. return _this;
  63927. }
  63928. _this._engine = scene.getEngine();
  63929. _this.name = name;
  63930. _this.isRenderTarget = true;
  63931. _this._initialSizeParameter = size;
  63932. _this._processSizeParameter(size);
  63933. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63934. });
  63935. _this._generateMipMaps = generateMipMaps ? true : false;
  63936. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63937. // Rendering groups
  63938. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63939. if (isMulti) {
  63940. return _this;
  63941. }
  63942. _this._renderTargetOptions = {
  63943. generateMipMaps: generateMipMaps,
  63944. type: type,
  63945. samplingMode: samplingMode,
  63946. generateDepthBuffer: generateDepthBuffer,
  63947. generateStencilBuffer: generateStencilBuffer
  63948. };
  63949. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63950. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63951. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63952. }
  63953. if (isCube) {
  63954. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63955. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63956. _this._textureMatrix = BABYLON.Matrix.Identity();
  63957. }
  63958. else {
  63959. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63960. }
  63961. return _this;
  63962. }
  63963. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63964. get: function () {
  63965. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63966. },
  63967. enumerable: true,
  63968. configurable: true
  63969. });
  63970. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63971. get: function () {
  63972. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63973. },
  63974. enumerable: true,
  63975. configurable: true
  63976. });
  63977. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63978. get: function () {
  63979. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63980. },
  63981. enumerable: true,
  63982. configurable: true
  63983. });
  63984. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63985. set: function (callback) {
  63986. if (this._onAfterUnbindObserver) {
  63987. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63988. }
  63989. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63995. set: function (callback) {
  63996. if (this._onBeforeRenderObserver) {
  63997. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63998. }
  63999. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64005. set: function (callback) {
  64006. if (this._onAfterRenderObserver) {
  64007. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64008. }
  64009. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64010. },
  64011. enumerable: true,
  64012. configurable: true
  64013. });
  64014. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64015. set: function (callback) {
  64016. if (this._onClearObserver) {
  64017. this.onClearObservable.remove(this._onClearObserver);
  64018. }
  64019. this._onClearObserver = this.onClearObservable.add(callback);
  64020. },
  64021. enumerable: true,
  64022. configurable: true
  64023. });
  64024. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64025. get: function () {
  64026. return this._renderTargetOptions;
  64027. },
  64028. enumerable: true,
  64029. configurable: true
  64030. });
  64031. RenderTargetTexture.prototype._onRatioRescale = function () {
  64032. if (this._sizeRatio) {
  64033. this.resize(this._initialSizeParameter);
  64034. }
  64035. };
  64036. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64037. get: function () {
  64038. return this._boundingBoxSize;
  64039. },
  64040. /**
  64041. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64042. * When defined, the cubemap will switch to local mode
  64043. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64044. * @example https://www.babylonjs-playground.com/#RNASML
  64045. */
  64046. set: function (value) {
  64047. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64048. return;
  64049. }
  64050. this._boundingBoxSize = value;
  64051. var scene = this.getScene();
  64052. if (scene) {
  64053. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64054. }
  64055. },
  64056. enumerable: true,
  64057. configurable: true
  64058. });
  64059. /**
  64060. * Creates a depth stencil texture.
  64061. * This is only available in WebGL 2 or with the depth texture extension available.
  64062. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64063. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64064. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64065. */
  64066. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64067. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64068. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64069. if (generateStencil === void 0) { generateStencil = false; }
  64070. if (!this.getScene()) {
  64071. return;
  64072. }
  64073. var engine = this.getScene().getEngine();
  64074. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64075. bilinearFiltering: bilinearFiltering,
  64076. comparisonFunction: comparisonFunction,
  64077. generateStencil: generateStencil,
  64078. isCube: this.isCube
  64079. });
  64080. engine.setFrameBufferDepthStencilTexture(this);
  64081. };
  64082. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64083. if (size.ratio) {
  64084. this._sizeRatio = size.ratio;
  64085. this._size = {
  64086. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64087. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64088. };
  64089. }
  64090. else {
  64091. this._size = size;
  64092. }
  64093. };
  64094. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64095. get: function () {
  64096. return this._samples;
  64097. },
  64098. set: function (value) {
  64099. if (this._samples === value) {
  64100. return;
  64101. }
  64102. var scene = this.getScene();
  64103. if (!scene) {
  64104. return;
  64105. }
  64106. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64107. },
  64108. enumerable: true,
  64109. configurable: true
  64110. });
  64111. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64112. this._currentRefreshId = -1;
  64113. };
  64114. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64115. get: function () {
  64116. return this._refreshRate;
  64117. },
  64118. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64119. set: function (value) {
  64120. this._refreshRate = value;
  64121. this.resetRefreshCounter();
  64122. },
  64123. enumerable: true,
  64124. configurable: true
  64125. });
  64126. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64127. if (!this._postProcessManager) {
  64128. var scene = this.getScene();
  64129. if (!scene) {
  64130. return;
  64131. }
  64132. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64133. this._postProcesses = new Array();
  64134. }
  64135. this._postProcesses.push(postProcess);
  64136. this._postProcesses[0].autoClear = false;
  64137. };
  64138. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64139. if (!this._postProcesses) {
  64140. return;
  64141. }
  64142. if (dispose) {
  64143. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64144. var postProcess = _a[_i];
  64145. postProcess.dispose();
  64146. }
  64147. }
  64148. this._postProcesses = [];
  64149. };
  64150. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64151. if (!this._postProcesses) {
  64152. return;
  64153. }
  64154. var index = this._postProcesses.indexOf(postProcess);
  64155. if (index === -1) {
  64156. return;
  64157. }
  64158. this._postProcesses.splice(index, 1);
  64159. if (this._postProcesses.length > 0) {
  64160. this._postProcesses[0].autoClear = false;
  64161. }
  64162. };
  64163. RenderTargetTexture.prototype._shouldRender = function () {
  64164. if (this._currentRefreshId === -1) { // At least render once
  64165. this._currentRefreshId = 1;
  64166. return true;
  64167. }
  64168. if (this.refreshRate === this._currentRefreshId) {
  64169. this._currentRefreshId = 1;
  64170. return true;
  64171. }
  64172. this._currentRefreshId++;
  64173. return false;
  64174. };
  64175. RenderTargetTexture.prototype.getRenderSize = function () {
  64176. if (this._size.width) {
  64177. return this._size.width;
  64178. }
  64179. return this._size;
  64180. };
  64181. RenderTargetTexture.prototype.getRenderWidth = function () {
  64182. if (this._size.width) {
  64183. return this._size.width;
  64184. }
  64185. return this._size;
  64186. };
  64187. RenderTargetTexture.prototype.getRenderHeight = function () {
  64188. if (this._size.width) {
  64189. return this._size.height;
  64190. }
  64191. return this._size;
  64192. };
  64193. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64194. get: function () {
  64195. return true;
  64196. },
  64197. enumerable: true,
  64198. configurable: true
  64199. });
  64200. RenderTargetTexture.prototype.scale = function (ratio) {
  64201. var newSize = this.getRenderSize() * ratio;
  64202. this.resize(newSize);
  64203. };
  64204. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64205. if (this.isCube) {
  64206. return this._textureMatrix;
  64207. }
  64208. return _super.prototype.getReflectionTextureMatrix.call(this);
  64209. };
  64210. RenderTargetTexture.prototype.resize = function (size) {
  64211. this.releaseInternalTexture();
  64212. var scene = this.getScene();
  64213. if (!scene) {
  64214. return;
  64215. }
  64216. this._processSizeParameter(size);
  64217. if (this.isCube) {
  64218. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64219. }
  64220. else {
  64221. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64222. }
  64223. };
  64224. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64225. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64226. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64227. var scene = this.getScene();
  64228. if (!scene) {
  64229. return;
  64230. }
  64231. var engine = scene.getEngine();
  64232. if (this.useCameraPostProcesses !== undefined) {
  64233. useCameraPostProcess = this.useCameraPostProcesses;
  64234. }
  64235. if (this._waitingRenderList) {
  64236. this.renderList = [];
  64237. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64238. var id = this._waitingRenderList[index];
  64239. var mesh_1 = scene.getMeshByID(id);
  64240. if (mesh_1) {
  64241. this.renderList.push(mesh_1);
  64242. }
  64243. }
  64244. delete this._waitingRenderList;
  64245. }
  64246. // Is predicate defined?
  64247. if (this.renderListPredicate) {
  64248. if (this.renderList) {
  64249. this.renderList.splice(0); // Clear previous renderList
  64250. }
  64251. else {
  64252. this.renderList = [];
  64253. }
  64254. var scene = this.getScene();
  64255. if (!scene) {
  64256. return;
  64257. }
  64258. var sceneMeshes = scene.meshes;
  64259. for (var index = 0; index < sceneMeshes.length; index++) {
  64260. var mesh = sceneMeshes[index];
  64261. if (this.renderListPredicate(mesh)) {
  64262. this.renderList.push(mesh);
  64263. }
  64264. }
  64265. }
  64266. this.onBeforeBindObservable.notifyObservers(this);
  64267. // Set custom projection.
  64268. // Needs to be before binding to prevent changing the aspect ratio.
  64269. var camera;
  64270. if (this.activeCamera) {
  64271. camera = this.activeCamera;
  64272. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64273. if (this.activeCamera !== scene.activeCamera) {
  64274. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64275. }
  64276. }
  64277. else {
  64278. camera = scene.activeCamera;
  64279. if (camera) {
  64280. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64281. }
  64282. }
  64283. // Prepare renderingManager
  64284. this._renderingManager.reset();
  64285. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64286. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64287. var sceneRenderId = scene.getRenderId();
  64288. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64289. var mesh = currentRenderList[meshIndex];
  64290. if (mesh) {
  64291. if (!mesh.isReady(this.refreshRate === 0)) {
  64292. this.resetRefreshCounter();
  64293. continue;
  64294. }
  64295. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64296. var isMasked = void 0;
  64297. if (!this.renderList && camera) {
  64298. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64299. }
  64300. else {
  64301. isMasked = false;
  64302. }
  64303. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64304. mesh._activate(sceneRenderId);
  64305. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64306. var subMesh = mesh.subMeshes[subIndex];
  64307. scene._activeIndices.addCount(subMesh.indexCount, false);
  64308. this._renderingManager.dispatch(subMesh, mesh);
  64309. }
  64310. }
  64311. }
  64312. }
  64313. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64314. var particleSystem = scene.particleSystems[particleIndex];
  64315. var emitter = particleSystem.emitter;
  64316. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64317. continue;
  64318. }
  64319. if (currentRenderList.indexOf(emitter) >= 0) {
  64320. this._renderingManager.dispatchParticles(particleSystem);
  64321. }
  64322. }
  64323. if (this.isCube) {
  64324. for (var face = 0; face < 6; face++) {
  64325. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64326. scene.incrementRenderId();
  64327. scene.resetCachedMaterial();
  64328. }
  64329. }
  64330. else {
  64331. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64332. }
  64333. this.onAfterUnbindObservable.notifyObservers(this);
  64334. if (scene.activeCamera) {
  64335. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64336. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64337. }
  64338. engine.setViewport(scene.activeCamera.viewport);
  64339. }
  64340. scene.resetCachedMaterial();
  64341. };
  64342. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64343. var minimum = 128;
  64344. var x = renderDimension * scale;
  64345. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64346. // Ensure we don't exceed the render dimension (while staying POT)
  64347. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64348. };
  64349. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64350. var _this = this;
  64351. if (!this._texture) {
  64352. return;
  64353. }
  64354. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64355. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64356. });
  64357. };
  64358. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64359. var scene = this.getScene();
  64360. if (!scene) {
  64361. return;
  64362. }
  64363. var engine = scene.getEngine();
  64364. if (!this._texture) {
  64365. return;
  64366. }
  64367. // Bind
  64368. if (this._postProcessManager) {
  64369. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64370. }
  64371. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64372. if (this._texture) {
  64373. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64374. }
  64375. }
  64376. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64377. // Clear
  64378. if (this.onClearObservable.hasObservers()) {
  64379. this.onClearObservable.notifyObservers(engine);
  64380. }
  64381. else {
  64382. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64383. }
  64384. if (!this._doNotChangeAspectRatio) {
  64385. scene.updateTransformMatrix(true);
  64386. }
  64387. // Render
  64388. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64389. if (this._postProcessManager) {
  64390. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64391. }
  64392. else if (useCameraPostProcess) {
  64393. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64394. }
  64395. if (!this._doNotChangeAspectRatio) {
  64396. scene.updateTransformMatrix(true);
  64397. }
  64398. // Dump ?
  64399. if (dumpForDebug) {
  64400. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64401. }
  64402. // Unbind
  64403. if (!this.isCube || faceIndex === 5) {
  64404. if (this.isCube) {
  64405. if (faceIndex === 5) {
  64406. engine.generateMipMapsForCubemap(this._texture);
  64407. }
  64408. }
  64409. this.unbindFrameBuffer(engine, faceIndex);
  64410. }
  64411. else {
  64412. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64413. }
  64414. };
  64415. /**
  64416. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64417. * This allowed control for front to back rendering or reversly depending of the special needs.
  64418. *
  64419. * @param renderingGroupId The rendering group id corresponding to its index
  64420. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64421. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64422. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64423. */
  64424. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64425. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64426. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64427. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64428. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64429. };
  64430. /**
  64431. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64432. *
  64433. * @param renderingGroupId The rendering group id corresponding to its index
  64434. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64435. */
  64436. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64437. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64438. };
  64439. RenderTargetTexture.prototype.clone = function () {
  64440. var textureSize = this.getSize();
  64441. 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);
  64442. // Base texture
  64443. newTexture.hasAlpha = this.hasAlpha;
  64444. newTexture.level = this.level;
  64445. // RenderTarget Texture
  64446. newTexture.coordinatesMode = this.coordinatesMode;
  64447. if (this.renderList) {
  64448. newTexture.renderList = this.renderList.slice(0);
  64449. }
  64450. return newTexture;
  64451. };
  64452. RenderTargetTexture.prototype.serialize = function () {
  64453. if (!this.name) {
  64454. return null;
  64455. }
  64456. var serializationObject = _super.prototype.serialize.call(this);
  64457. serializationObject.renderTargetSize = this.getRenderSize();
  64458. serializationObject.renderList = [];
  64459. if (this.renderList) {
  64460. for (var index = 0; index < this.renderList.length; index++) {
  64461. serializationObject.renderList.push(this.renderList[index].id);
  64462. }
  64463. }
  64464. return serializationObject;
  64465. };
  64466. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64467. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64468. var objBuffer = this.getInternalTexture();
  64469. var scene = this.getScene();
  64470. if (objBuffer && scene) {
  64471. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64472. }
  64473. };
  64474. RenderTargetTexture.prototype.dispose = function () {
  64475. if (this._postProcessManager) {
  64476. this._postProcessManager.dispose();
  64477. this._postProcessManager = null;
  64478. }
  64479. this.clearPostProcesses(true);
  64480. if (this._resizeObserver) {
  64481. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64482. this._resizeObserver = null;
  64483. }
  64484. this.renderList = null;
  64485. // Remove from custom render targets
  64486. var scene = this.getScene();
  64487. if (!scene) {
  64488. return;
  64489. }
  64490. var index = scene.customRenderTargets.indexOf(this);
  64491. if (index >= 0) {
  64492. scene.customRenderTargets.splice(index, 1);
  64493. }
  64494. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64495. var camera = _a[_i];
  64496. index = camera.customRenderTargets.indexOf(this);
  64497. if (index >= 0) {
  64498. camera.customRenderTargets.splice(index, 1);
  64499. }
  64500. }
  64501. _super.prototype.dispose.call(this);
  64502. };
  64503. RenderTargetTexture.prototype._rebuild = function () {
  64504. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64505. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64506. }
  64507. if (this._postProcessManager) {
  64508. this._postProcessManager._rebuild();
  64509. }
  64510. };
  64511. /**
  64512. * Clear the info related to rendering groups preventing retention point in material dispose.
  64513. */
  64514. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64515. if (this._renderingManager) {
  64516. this._renderingManager.freeRenderingGroups();
  64517. }
  64518. };
  64519. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64520. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64521. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64522. return RenderTargetTexture;
  64523. }(BABYLON.Texture));
  64524. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64525. })(BABYLON || (BABYLON = {}));
  64526. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64527. var BABYLON;
  64528. (function (BABYLON) {
  64529. ;
  64530. var MultiRenderTarget = /** @class */ (function (_super) {
  64531. __extends(MultiRenderTarget, _super);
  64532. function MultiRenderTarget(name, size, count, scene, options) {
  64533. var _this = this;
  64534. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64535. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64536. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64537. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64538. _this._engine = scene.getEngine();
  64539. if (!_this.isSupported) {
  64540. _this.dispose();
  64541. return;
  64542. }
  64543. var types = [];
  64544. var samplingModes = [];
  64545. for (var i = 0; i < count; i++) {
  64546. if (options && options.types && options.types[i] !== undefined) {
  64547. types.push(options.types[i]);
  64548. }
  64549. else {
  64550. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64551. }
  64552. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64553. samplingModes.push(options.samplingModes[i]);
  64554. }
  64555. else {
  64556. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64557. }
  64558. }
  64559. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64560. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64561. _this._size = size;
  64562. _this._multiRenderTargetOptions = {
  64563. samplingModes: samplingModes,
  64564. generateMipMaps: generateMipMaps,
  64565. generateDepthBuffer: generateDepthBuffer,
  64566. generateStencilBuffer: generateStencilBuffer,
  64567. generateDepthTexture: generateDepthTexture,
  64568. types: types,
  64569. textureCount: count
  64570. };
  64571. _this._createInternalTextures();
  64572. _this._createTextures();
  64573. return _this;
  64574. }
  64575. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64576. get: function () {
  64577. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64578. },
  64579. enumerable: true,
  64580. configurable: true
  64581. });
  64582. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64583. get: function () {
  64584. return this._textures;
  64585. },
  64586. enumerable: true,
  64587. configurable: true
  64588. });
  64589. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64590. get: function () {
  64591. return this._textures[this._textures.length - 1];
  64592. },
  64593. enumerable: true,
  64594. configurable: true
  64595. });
  64596. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64597. set: function (wrap) {
  64598. if (this._textures) {
  64599. for (var i = 0; i < this._textures.length; i++) {
  64600. this._textures[i].wrapU = wrap;
  64601. }
  64602. }
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64608. set: function (wrap) {
  64609. if (this._textures) {
  64610. for (var i = 0; i < this._textures.length; i++) {
  64611. this._textures[i].wrapV = wrap;
  64612. }
  64613. }
  64614. },
  64615. enumerable: true,
  64616. configurable: true
  64617. });
  64618. MultiRenderTarget.prototype._rebuild = function () {
  64619. this.releaseInternalTextures();
  64620. this._createInternalTextures();
  64621. for (var i = 0; i < this._internalTextures.length; i++) {
  64622. var texture = this._textures[i];
  64623. texture._texture = this._internalTextures[i];
  64624. }
  64625. // Keeps references to frame buffer and stencil/depth buffer
  64626. this._texture = this._internalTextures[0];
  64627. };
  64628. MultiRenderTarget.prototype._createInternalTextures = function () {
  64629. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64630. };
  64631. MultiRenderTarget.prototype._createTextures = function () {
  64632. this._textures = [];
  64633. for (var i = 0; i < this._internalTextures.length; i++) {
  64634. var texture = new BABYLON.Texture(null, this.getScene());
  64635. texture._texture = this._internalTextures[i];
  64636. this._textures.push(texture);
  64637. }
  64638. // Keeps references to frame buffer and stencil/depth buffer
  64639. this._texture = this._internalTextures[0];
  64640. };
  64641. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64642. get: function () {
  64643. return this._samples;
  64644. },
  64645. set: function (value) {
  64646. if (this._samples === value) {
  64647. return;
  64648. }
  64649. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64650. },
  64651. enumerable: true,
  64652. configurable: true
  64653. });
  64654. MultiRenderTarget.prototype.resize = function (size) {
  64655. this.releaseInternalTextures();
  64656. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64657. this._createInternalTextures();
  64658. };
  64659. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64660. var _this = this;
  64661. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64662. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64663. });
  64664. };
  64665. MultiRenderTarget.prototype.dispose = function () {
  64666. this.releaseInternalTextures();
  64667. _super.prototype.dispose.call(this);
  64668. };
  64669. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64670. if (!this._internalTextures) {
  64671. return;
  64672. }
  64673. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64674. if (this._internalTextures[i] !== undefined) {
  64675. this._internalTextures[i].dispose();
  64676. this._internalTextures.splice(i, 1);
  64677. }
  64678. }
  64679. };
  64680. return MultiRenderTarget;
  64681. }(BABYLON.RenderTargetTexture));
  64682. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64683. })(BABYLON || (BABYLON = {}));
  64684. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64685. var BABYLON;
  64686. (function (BABYLON) {
  64687. var MirrorTexture = /** @class */ (function (_super) {
  64688. __extends(MirrorTexture, _super);
  64689. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64690. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64692. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64693. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64694. _this.scene = scene;
  64695. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64696. _this._transformMatrix = BABYLON.Matrix.Zero();
  64697. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64698. _this._adaptiveBlurKernel = 0;
  64699. _this._blurKernelX = 0;
  64700. _this._blurKernelY = 0;
  64701. _this._blurRatio = 1.0;
  64702. _this.ignoreCameraViewport = true;
  64703. _this._updateGammaSpace();
  64704. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64705. _this._updateGammaSpace;
  64706. });
  64707. _this.onBeforeRenderObservable.add(function () {
  64708. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64709. _this._savedViewMatrix = scene.getViewMatrix();
  64710. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64711. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64712. scene.clipPlane = _this.mirrorPlane;
  64713. scene.getEngine().cullBackFaces = false;
  64714. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64715. });
  64716. _this.onAfterRenderObservable.add(function () {
  64717. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64718. scene.getEngine().cullBackFaces = true;
  64719. scene._mirroredCameraPosition = null;
  64720. delete scene.clipPlane;
  64721. });
  64722. return _this;
  64723. }
  64724. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64725. get: function () {
  64726. return this._blurRatio;
  64727. },
  64728. set: function (value) {
  64729. if (this._blurRatio === value) {
  64730. return;
  64731. }
  64732. this._blurRatio = value;
  64733. this._preparePostProcesses();
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64739. set: function (value) {
  64740. this._adaptiveBlurKernel = value;
  64741. this._autoComputeBlurKernel();
  64742. },
  64743. enumerable: true,
  64744. configurable: true
  64745. });
  64746. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64747. set: function (value) {
  64748. this.blurKernelX = value;
  64749. this.blurKernelY = value;
  64750. },
  64751. enumerable: true,
  64752. configurable: true
  64753. });
  64754. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64755. get: function () {
  64756. return this._blurKernelX;
  64757. },
  64758. set: function (value) {
  64759. if (this._blurKernelX === value) {
  64760. return;
  64761. }
  64762. this._blurKernelX = value;
  64763. this._preparePostProcesses();
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64769. get: function () {
  64770. return this._blurKernelY;
  64771. },
  64772. set: function (value) {
  64773. if (this._blurKernelY === value) {
  64774. return;
  64775. }
  64776. this._blurKernelY = value;
  64777. this._preparePostProcesses();
  64778. },
  64779. enumerable: true,
  64780. configurable: true
  64781. });
  64782. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64783. var engine = this.getScene().getEngine();
  64784. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64785. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64786. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64787. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64788. };
  64789. MirrorTexture.prototype._onRatioRescale = function () {
  64790. if (this._sizeRatio) {
  64791. this.resize(this._initialSizeParameter);
  64792. if (!this._adaptiveBlurKernel) {
  64793. this._preparePostProcesses();
  64794. }
  64795. }
  64796. if (this._adaptiveBlurKernel) {
  64797. this._autoComputeBlurKernel();
  64798. }
  64799. };
  64800. MirrorTexture.prototype._updateGammaSpace = function () {
  64801. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64802. };
  64803. MirrorTexture.prototype._preparePostProcesses = function () {
  64804. this.clearPostProcesses(true);
  64805. if (this._blurKernelX && this._blurKernelY) {
  64806. var engine = this.getScene().getEngine();
  64807. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64808. 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);
  64809. this._blurX.autoClear = false;
  64810. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64811. this._blurX.inputTexture = this._texture;
  64812. }
  64813. else {
  64814. this._blurX.alwaysForcePOT = true;
  64815. }
  64816. 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);
  64817. this._blurY.autoClear = false;
  64818. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64819. this.addPostProcess(this._blurX);
  64820. this.addPostProcess(this._blurY);
  64821. }
  64822. else {
  64823. if (this._blurY) {
  64824. this.removePostProcess(this._blurY);
  64825. this._blurY.dispose();
  64826. this._blurY = null;
  64827. }
  64828. if (this._blurX) {
  64829. this.removePostProcess(this._blurX);
  64830. this._blurX.dispose();
  64831. this._blurX = null;
  64832. }
  64833. }
  64834. };
  64835. MirrorTexture.prototype.clone = function () {
  64836. var scene = this.getScene();
  64837. if (!scene) {
  64838. return this;
  64839. }
  64840. var textureSize = this.getSize();
  64841. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64842. // Base texture
  64843. newTexture.hasAlpha = this.hasAlpha;
  64844. newTexture.level = this.level;
  64845. // Mirror Texture
  64846. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64847. if (this.renderList) {
  64848. newTexture.renderList = this.renderList.slice(0);
  64849. }
  64850. return newTexture;
  64851. };
  64852. MirrorTexture.prototype.serialize = function () {
  64853. if (!this.name) {
  64854. return null;
  64855. }
  64856. var serializationObject = _super.prototype.serialize.call(this);
  64857. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64858. return serializationObject;
  64859. };
  64860. MirrorTexture.prototype.dispose = function () {
  64861. _super.prototype.dispose.call(this);
  64862. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64863. };
  64864. return MirrorTexture;
  64865. }(BABYLON.RenderTargetTexture));
  64866. BABYLON.MirrorTexture = MirrorTexture;
  64867. })(BABYLON || (BABYLON = {}));
  64868. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64869. var BABYLON;
  64870. (function (BABYLON) {
  64871. /**
  64872. * Creates a refraction texture used by refraction channel of the standard material.
  64873. * @param name the texture name
  64874. * @param size size of the underlying texture
  64875. * @param scene root scene
  64876. */
  64877. var RefractionTexture = /** @class */ (function (_super) {
  64878. __extends(RefractionTexture, _super);
  64879. function RefractionTexture(name, size, scene, generateMipMaps) {
  64880. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64881. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64882. _this.depth = 2.0;
  64883. _this.onBeforeRenderObservable.add(function () {
  64884. scene.clipPlane = _this.refractionPlane;
  64885. });
  64886. _this.onAfterRenderObservable.add(function () {
  64887. delete scene.clipPlane;
  64888. });
  64889. return _this;
  64890. }
  64891. RefractionTexture.prototype.clone = function () {
  64892. var scene = this.getScene();
  64893. if (!scene) {
  64894. return this;
  64895. }
  64896. var textureSize = this.getSize();
  64897. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64898. // Base texture
  64899. newTexture.hasAlpha = this.hasAlpha;
  64900. newTexture.level = this.level;
  64901. // Refraction Texture
  64902. newTexture.refractionPlane = this.refractionPlane.clone();
  64903. if (this.renderList) {
  64904. newTexture.renderList = this.renderList.slice(0);
  64905. }
  64906. newTexture.depth = this.depth;
  64907. return newTexture;
  64908. };
  64909. RefractionTexture.prototype.serialize = function () {
  64910. if (!this.name) {
  64911. return null;
  64912. }
  64913. var serializationObject = _super.prototype.serialize.call(this);
  64914. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64915. serializationObject.depth = this.depth;
  64916. return serializationObject;
  64917. };
  64918. return RefractionTexture;
  64919. }(BABYLON.RenderTargetTexture));
  64920. BABYLON.RefractionTexture = RefractionTexture;
  64921. })(BABYLON || (BABYLON = {}));
  64922. //# sourceMappingURL=babylon.refractionTexture.js.map
  64923. var BABYLON;
  64924. (function (BABYLON) {
  64925. /**
  64926. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64927. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64928. */
  64929. var DynamicTexture = /** @class */ (function (_super) {
  64930. __extends(DynamicTexture, _super);
  64931. /**
  64932. * Creates a {BABYLON.DynamicTexture}
  64933. * @param name defines the name of the texture
  64934. * @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
  64935. * @param scene defines the scene where you want the texture
  64936. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64937. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64938. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64939. */
  64940. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64941. if (scene === void 0) { scene = null; }
  64942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64943. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64944. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64945. _this.name = name;
  64946. _this._engine = _this.getScene().getEngine();
  64947. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64948. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64949. _this._generateMipMaps = generateMipMaps;
  64950. if (options.getContext) {
  64951. _this._canvas = options;
  64952. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64953. }
  64954. else {
  64955. _this._canvas = document.createElement("canvas");
  64956. if (options.width || options.width === 0) {
  64957. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64958. }
  64959. else {
  64960. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64961. }
  64962. }
  64963. var textureSize = _this.getSize();
  64964. _this._canvas.width = textureSize.width;
  64965. _this._canvas.height = textureSize.height;
  64966. _this._context = _this._canvas.getContext("2d");
  64967. return _this;
  64968. }
  64969. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64970. /**
  64971. * Gets the current state of canRescale
  64972. */
  64973. get: function () {
  64974. return true;
  64975. },
  64976. enumerable: true,
  64977. configurable: true
  64978. });
  64979. DynamicTexture.prototype._recreate = function (textureSize) {
  64980. this._canvas.width = textureSize.width;
  64981. this._canvas.height = textureSize.height;
  64982. this.releaseInternalTexture();
  64983. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64984. };
  64985. /**
  64986. * Scales the texture
  64987. * @param ratio the scale factor to apply to both width and height
  64988. */
  64989. DynamicTexture.prototype.scale = function (ratio) {
  64990. var textureSize = this.getSize();
  64991. textureSize.width *= ratio;
  64992. textureSize.height *= ratio;
  64993. this._recreate(textureSize);
  64994. };
  64995. /**
  64996. * Resizes the texture
  64997. * @param width the new width
  64998. * @param height the new height
  64999. */
  65000. DynamicTexture.prototype.scaleTo = function (width, height) {
  65001. var textureSize = this.getSize();
  65002. textureSize.width = width;
  65003. textureSize.height = height;
  65004. this._recreate(textureSize);
  65005. };
  65006. /**
  65007. * Gets the context of the canvas used by the texture
  65008. * @returns the canvas context of the dynamic texture
  65009. */
  65010. DynamicTexture.prototype.getContext = function () {
  65011. return this._context;
  65012. };
  65013. /**
  65014. * Clears the texture
  65015. */
  65016. DynamicTexture.prototype.clear = function () {
  65017. var size = this.getSize();
  65018. this._context.fillRect(0, 0, size.width, size.height);
  65019. };
  65020. /**
  65021. * Updates the texture
  65022. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65023. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65024. */
  65025. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65026. if (premulAlpha === void 0) { premulAlpha = false; }
  65027. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65028. };
  65029. /**
  65030. * Draws text onto the texture
  65031. * @param text defines the text to be drawn
  65032. * @param x defines the placement of the text from the left
  65033. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65034. * @param font defines the font to be used with font-style, font-size, font-name
  65035. * @param color defines the color used for the text
  65036. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65037. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65038. * @param update defines whether texture is immediately update (default is true)
  65039. */
  65040. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65041. if (update === void 0) { update = true; }
  65042. var size = this.getSize();
  65043. if (clearColor) {
  65044. this._context.fillStyle = clearColor;
  65045. this._context.fillRect(0, 0, size.width, size.height);
  65046. }
  65047. this._context.font = font;
  65048. if (x === null || x === undefined) {
  65049. var textSize = this._context.measureText(text);
  65050. x = (size.width - textSize.width) / 2;
  65051. }
  65052. if (y === null || y === undefined) {
  65053. var fontSize = parseInt((font.replace(/\D/g, '')));
  65054. y = (size.height / 2) + (fontSize / 3.65);
  65055. }
  65056. this._context.fillStyle = color;
  65057. this._context.fillText(text, x, y);
  65058. if (update) {
  65059. this.update(invertY);
  65060. }
  65061. };
  65062. /**
  65063. * Clones the texture
  65064. * @returns the clone of the texture.
  65065. */
  65066. DynamicTexture.prototype.clone = function () {
  65067. var scene = this.getScene();
  65068. if (!scene) {
  65069. return this;
  65070. }
  65071. var textureSize = this.getSize();
  65072. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65073. // Base texture
  65074. newTexture.hasAlpha = this.hasAlpha;
  65075. newTexture.level = this.level;
  65076. // Dynamic Texture
  65077. newTexture.wrapU = this.wrapU;
  65078. newTexture.wrapV = this.wrapV;
  65079. return newTexture;
  65080. };
  65081. /** @hidden */
  65082. DynamicTexture.prototype._rebuild = function () {
  65083. this.update();
  65084. };
  65085. return DynamicTexture;
  65086. }(BABYLON.Texture));
  65087. BABYLON.DynamicTexture = DynamicTexture;
  65088. })(BABYLON || (BABYLON = {}));
  65089. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65090. var BABYLON;
  65091. (function (BABYLON) {
  65092. var VideoTexture = /** @class */ (function (_super) {
  65093. __extends(VideoTexture, _super);
  65094. /**
  65095. * Creates a video texture.
  65096. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65097. * @param {string | null} name optional name, will detect from video source, if not defined
  65098. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65099. * @param {BABYLON.Scene} scene is obviously the current scene.
  65100. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65101. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65102. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65103. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65104. */
  65105. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65106. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65107. if (invertY === void 0) { invertY = false; }
  65108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65109. if (settings === void 0) { settings = {
  65110. autoPlay: true,
  65111. loop: true,
  65112. autoUpdateTexture: true,
  65113. }; }
  65114. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65115. _this._stillImageCaptured = false;
  65116. _this._createInternalTexture = function () {
  65117. if (_this._texture != null) {
  65118. return;
  65119. }
  65120. if (!_this._engine.needPOTTextures ||
  65121. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65122. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65123. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65124. }
  65125. else {
  65126. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65127. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65128. _this._generateMipMaps = false;
  65129. }
  65130. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65131. if (!_this.video.autoplay) {
  65132. var oldHandler_1 = _this.video.onplaying;
  65133. _this.video.onplaying = function () {
  65134. _this.video.onplaying = oldHandler_1;
  65135. _this._texture.isReady = true;
  65136. _this._updateInternalTexture();
  65137. _this.video.pause();
  65138. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65139. _this.onLoadObservable.notifyObservers(_this);
  65140. }
  65141. };
  65142. _this.video.play();
  65143. }
  65144. else {
  65145. _this._texture.isReady = true;
  65146. _this._updateInternalTexture();
  65147. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65148. _this.onLoadObservable.notifyObservers(_this);
  65149. }
  65150. }
  65151. };
  65152. _this.reset = function () {
  65153. if (_this._texture == null) {
  65154. return;
  65155. }
  65156. _this._texture.dispose();
  65157. _this._texture = null;
  65158. };
  65159. _this._updateInternalTexture = function (e) {
  65160. if (_this._texture == null || !_this._texture.isReady) {
  65161. return;
  65162. }
  65163. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65164. return;
  65165. }
  65166. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65167. };
  65168. _this._engine = _this.getScene().getEngine();
  65169. _this._generateMipMaps = generateMipMaps;
  65170. _this._samplingMode = samplingMode;
  65171. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65172. _this.name = name || _this._getName(src);
  65173. _this.video = _this._getVideo(src);
  65174. if (settings.autoPlay !== undefined) {
  65175. _this.video.autoplay = settings.autoPlay;
  65176. }
  65177. if (settings.loop !== undefined) {
  65178. _this.video.loop = settings.loop;
  65179. }
  65180. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65181. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65182. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65183. _this.video.addEventListener("emptied", _this.reset);
  65184. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65185. _this._createInternalTexture();
  65186. }
  65187. return _this;
  65188. }
  65189. VideoTexture.prototype._getName = function (src) {
  65190. if (src instanceof HTMLVideoElement) {
  65191. return src.currentSrc;
  65192. }
  65193. if (typeof src === "object") {
  65194. return src.toString();
  65195. }
  65196. return src;
  65197. };
  65198. ;
  65199. VideoTexture.prototype._getVideo = function (src) {
  65200. if (src instanceof HTMLVideoElement) {
  65201. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65202. return src;
  65203. }
  65204. var video = document.createElement("video");
  65205. if (typeof src === "string") {
  65206. BABYLON.Tools.SetCorsBehavior(src, video);
  65207. video.src = src;
  65208. }
  65209. else {
  65210. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65211. src.forEach(function (url) {
  65212. var source = document.createElement("source");
  65213. source.src = url;
  65214. video.appendChild(source);
  65215. });
  65216. }
  65217. return video;
  65218. };
  65219. ;
  65220. /**
  65221. * Internal method to initiate `update`.
  65222. */
  65223. VideoTexture.prototype._rebuild = function () {
  65224. this.update();
  65225. };
  65226. /**
  65227. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65228. */
  65229. VideoTexture.prototype.update = function () {
  65230. if (!this.autoUpdateTexture) {
  65231. // Expecting user to call `updateTexture` manually
  65232. return;
  65233. }
  65234. this.updateTexture(true);
  65235. };
  65236. /**
  65237. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65238. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65239. */
  65240. VideoTexture.prototype.updateTexture = function (isVisible) {
  65241. if (!isVisible) {
  65242. return;
  65243. }
  65244. if (this.video.paused && this._stillImageCaptured) {
  65245. return;
  65246. }
  65247. this._stillImageCaptured = true;
  65248. this._updateInternalTexture();
  65249. };
  65250. /**
  65251. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65252. * @param url New url.
  65253. */
  65254. VideoTexture.prototype.updateURL = function (url) {
  65255. this.video.src = url;
  65256. };
  65257. VideoTexture.prototype.dispose = function () {
  65258. _super.prototype.dispose.call(this);
  65259. this.video.removeEventListener("canplay", this._createInternalTexture);
  65260. this.video.removeEventListener("paused", this._updateInternalTexture);
  65261. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65262. this.video.removeEventListener("emptied", this.reset);
  65263. this.video.pause();
  65264. };
  65265. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65266. var video = document.createElement("video");
  65267. var constraintsDeviceId;
  65268. if (constraints && constraints.deviceId) {
  65269. constraintsDeviceId = {
  65270. exact: constraints.deviceId,
  65271. };
  65272. }
  65273. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65274. if (navigator.mediaDevices) {
  65275. navigator.mediaDevices.getUserMedia({ video: constraints })
  65276. .then(function (stream) {
  65277. if (video.mozSrcObject !== undefined) {
  65278. // hack for Firefox < 19
  65279. video.mozSrcObject = stream;
  65280. }
  65281. else {
  65282. video.srcObject = stream;
  65283. }
  65284. var onPlaying = function () {
  65285. if (onReady) {
  65286. onReady(new VideoTexture("video", video, scene, true, true));
  65287. }
  65288. video.removeEventListener("playing", onPlaying);
  65289. };
  65290. video.addEventListener("playing", onPlaying);
  65291. video.play();
  65292. })
  65293. .catch(function (err) {
  65294. BABYLON.Tools.Error(err.name);
  65295. });
  65296. }
  65297. else {
  65298. navigator.getUserMedia =
  65299. navigator.getUserMedia ||
  65300. navigator.webkitGetUserMedia ||
  65301. navigator.mozGetUserMedia ||
  65302. navigator.msGetUserMedia;
  65303. if (navigator.getUserMedia) {
  65304. navigator.getUserMedia({
  65305. video: {
  65306. deviceId: constraintsDeviceId,
  65307. width: {
  65308. min: (constraints && constraints.minWidth) || 256,
  65309. max: (constraints && constraints.maxWidth) || 640,
  65310. },
  65311. height: {
  65312. min: (constraints && constraints.minHeight) || 256,
  65313. max: (constraints && constraints.maxHeight) || 480,
  65314. },
  65315. },
  65316. }, function (stream) {
  65317. if (video.mozSrcObject !== undefined) {
  65318. // hack for Firefox < 19
  65319. video.mozSrcObject = stream;
  65320. }
  65321. else {
  65322. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65323. }
  65324. video.play();
  65325. if (onReady) {
  65326. onReady(new VideoTexture("video", video, scene, true, true));
  65327. }
  65328. }, function (e) {
  65329. BABYLON.Tools.Error(e.name);
  65330. });
  65331. }
  65332. }
  65333. };
  65334. return VideoTexture;
  65335. }(BABYLON.Texture));
  65336. BABYLON.VideoTexture = VideoTexture;
  65337. })(BABYLON || (BABYLON = {}));
  65338. //# sourceMappingURL=babylon.videoTexture.js.map
  65339. var BABYLON;
  65340. (function (BABYLON) {
  65341. var RawTexture = /** @class */ (function (_super) {
  65342. __extends(RawTexture, _super);
  65343. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65344. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65345. if (invertY === void 0) { invertY = false; }
  65346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65347. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65348. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65349. _this.format = format;
  65350. _this._engine = scene.getEngine();
  65351. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65352. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65353. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65354. return _this;
  65355. }
  65356. RawTexture.prototype.update = function (data) {
  65357. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65358. };
  65359. // Statics
  65360. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65361. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65362. if (invertY === void 0) { invertY = false; }
  65363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65364. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65365. };
  65366. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65367. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65368. if (invertY === void 0) { invertY = false; }
  65369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65370. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65371. };
  65372. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65373. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65374. if (invertY === void 0) { invertY = false; }
  65375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65376. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65377. };
  65378. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65379. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65380. if (invertY === void 0) { invertY = false; }
  65381. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65382. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65383. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65384. };
  65385. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65387. if (invertY === void 0) { invertY = false; }
  65388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65389. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65390. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65391. };
  65392. return RawTexture;
  65393. }(BABYLON.Texture));
  65394. BABYLON.RawTexture = RawTexture;
  65395. })(BABYLON || (BABYLON = {}));
  65396. //# sourceMappingURL=babylon.rawTexture.js.map
  65397. var BABYLON;
  65398. (function (BABYLON) {
  65399. /**
  65400. * Class used to store 3D textures containing user data
  65401. */
  65402. var RawTexture3D = /** @class */ (function (_super) {
  65403. __extends(RawTexture3D, _super);
  65404. /**
  65405. * Create a new RawTexture3D
  65406. * @param data defines the data of the texture
  65407. * @param width defines the width of the texture
  65408. * @param height defines the height of the texture
  65409. * @param depth defines the depth of the texture
  65410. * @param format defines the texture format to use
  65411. * @param scene defines the hosting scene
  65412. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65413. * @param invertY defines if texture must be stored with Y axis inverted
  65414. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65415. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65416. */
  65417. function RawTexture3D(data, width, height, depth,
  65418. /** Gets or sets the texture format to use */
  65419. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65420. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65421. if (invertY === void 0) { invertY = false; }
  65422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65423. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65424. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65425. _this.format = format;
  65426. _this._engine = scene.getEngine();
  65427. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65428. _this.is3D = true;
  65429. return _this;
  65430. }
  65431. /**
  65432. * Update the texture with new data
  65433. * @param data defines the data to store in the texture
  65434. */
  65435. RawTexture3D.prototype.update = function (data) {
  65436. if (!this._texture) {
  65437. return;
  65438. }
  65439. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65440. };
  65441. return RawTexture3D;
  65442. }(BABYLON.Texture));
  65443. BABYLON.RawTexture3D = RawTexture3D;
  65444. })(BABYLON || (BABYLON = {}));
  65445. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65446. var BABYLON;
  65447. (function (BABYLON) {
  65448. /**
  65449. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65450. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65451. */
  65452. var PostProcess = /** @class */ (function () {
  65453. /**
  65454. * Creates a new instance PostProcess
  65455. * @param name The name of the PostProcess.
  65456. * @param fragmentUrl The url of the fragment shader to be used.
  65457. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65458. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65459. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65460. * @param camera The camera to apply the render pass to.
  65461. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65462. * @param engine The engine which the post process will be applied. (default: current engine)
  65463. * @param reusable If the post process can be reused on the same frame. (default: false)
  65464. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65465. * @param textureType Type of textures used when performing the post process. (default: 0)
  65466. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65467. * @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
  65468. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65469. */
  65470. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65472. if (defines === void 0) { defines = null; }
  65473. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65474. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65475. if (blockCompilation === void 0) { blockCompilation = false; }
  65476. this.name = name;
  65477. /**
  65478. * Width of the texture to apply the post process on
  65479. */
  65480. this.width = -1;
  65481. /**
  65482. * Height of the texture to apply the post process on
  65483. */
  65484. this.height = -1;
  65485. /**
  65486. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65487. */
  65488. this._outputTexture = null;
  65489. /**
  65490. * If the buffer needs to be cleared before applying the post process. (default: true)
  65491. * Should be set to false if shader will overwrite all previous pixels.
  65492. */
  65493. this.autoClear = true;
  65494. /**
  65495. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65496. */
  65497. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65498. /**
  65499. * Animations to be used for the post processing
  65500. */
  65501. this.animations = new Array();
  65502. /**
  65503. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65504. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65505. */
  65506. this.enablePixelPerfectMode = false;
  65507. /**
  65508. * Force the postprocess to be applied without taking in account viewport
  65509. */
  65510. this.forceFullscreenViewport = true;
  65511. /**
  65512. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65513. *
  65514. * | Value | Type | Description |
  65515. * | ----- | ----------------------------------- | ----------- |
  65516. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65517. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65518. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65519. *
  65520. */
  65521. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65522. /**
  65523. * Force textures to be a power of two (default: false)
  65524. */
  65525. this.alwaysForcePOT = false;
  65526. /**
  65527. * Number of sample textures (default: 1)
  65528. */
  65529. this.samples = 1;
  65530. /**
  65531. * Modify the scale of the post process to be the same as the viewport (default: false)
  65532. */
  65533. this.adaptScaleToCurrentViewport = false;
  65534. this._reusable = false;
  65535. /**
  65536. * Smart array of input and output textures for the post process.
  65537. */
  65538. this._textures = new BABYLON.SmartArray(2);
  65539. /**
  65540. * The index in _textures that corresponds to the output texture.
  65541. */
  65542. this._currentRenderTextureInd = 0;
  65543. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65544. this._texelSize = BABYLON.Vector2.Zero();
  65545. // Events
  65546. /**
  65547. * An event triggered when the postprocess is activated.
  65548. */
  65549. this.onActivateObservable = new BABYLON.Observable();
  65550. /**
  65551. * An event triggered when the postprocess changes its size.
  65552. */
  65553. this.onSizeChangedObservable = new BABYLON.Observable();
  65554. /**
  65555. * An event triggered when the postprocess applies its effect.
  65556. */
  65557. this.onApplyObservable = new BABYLON.Observable();
  65558. /**
  65559. * An event triggered before rendering the postprocess
  65560. */
  65561. this.onBeforeRenderObservable = new BABYLON.Observable();
  65562. /**
  65563. * An event triggered after rendering the postprocess
  65564. */
  65565. this.onAfterRenderObservable = new BABYLON.Observable();
  65566. if (camera != null) {
  65567. this._camera = camera;
  65568. this._scene = camera.getScene();
  65569. camera.attachPostProcess(this);
  65570. this._engine = this._scene.getEngine();
  65571. this._scene.postProcesses.push(this);
  65572. }
  65573. else if (engine) {
  65574. this._engine = engine;
  65575. this._engine.postProcesses.push(this);
  65576. }
  65577. this._options = options;
  65578. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65579. this._reusable = reusable || false;
  65580. this._textureType = textureType;
  65581. this._samplers = samplers || [];
  65582. this._samplers.push("textureSampler");
  65583. this._fragmentUrl = fragmentUrl;
  65584. this._vertexUrl = vertexUrl;
  65585. this._parameters = parameters || [];
  65586. this._parameters.push("scale");
  65587. this._indexParameters = indexParameters;
  65588. if (!blockCompilation) {
  65589. this.updateEffect(defines);
  65590. }
  65591. }
  65592. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65593. /**
  65594. * A function that is added to the onActivateObservable
  65595. */
  65596. set: function (callback) {
  65597. if (this._onActivateObserver) {
  65598. this.onActivateObservable.remove(this._onActivateObserver);
  65599. }
  65600. if (callback) {
  65601. this._onActivateObserver = this.onActivateObservable.add(callback);
  65602. }
  65603. },
  65604. enumerable: true,
  65605. configurable: true
  65606. });
  65607. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65608. /**
  65609. * A function that is added to the onSizeChangedObservable
  65610. */
  65611. set: function (callback) {
  65612. if (this._onSizeChangedObserver) {
  65613. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65614. }
  65615. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65616. },
  65617. enumerable: true,
  65618. configurable: true
  65619. });
  65620. Object.defineProperty(PostProcess.prototype, "onApply", {
  65621. /**
  65622. * A function that is added to the onApplyObservable
  65623. */
  65624. set: function (callback) {
  65625. if (this._onApplyObserver) {
  65626. this.onApplyObservable.remove(this._onApplyObserver);
  65627. }
  65628. this._onApplyObserver = this.onApplyObservable.add(callback);
  65629. },
  65630. enumerable: true,
  65631. configurable: true
  65632. });
  65633. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65634. /**
  65635. * A function that is added to the onBeforeRenderObservable
  65636. */
  65637. set: function (callback) {
  65638. if (this._onBeforeRenderObserver) {
  65639. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65640. }
  65641. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65642. },
  65643. enumerable: true,
  65644. configurable: true
  65645. });
  65646. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65647. /**
  65648. * A function that is added to the onAfterRenderObservable
  65649. */
  65650. set: function (callback) {
  65651. if (this._onAfterRenderObserver) {
  65652. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65653. }
  65654. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65660. /**
  65661. * 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
  65662. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65663. */
  65664. get: function () {
  65665. return this._textures.data[this._currentRenderTextureInd];
  65666. },
  65667. set: function (value) {
  65668. this._forcedOutputTexture = value;
  65669. },
  65670. enumerable: true,
  65671. configurable: true
  65672. });
  65673. /**
  65674. * Gets the camera which post process is applied to.
  65675. * @returns The camera the post process is applied to.
  65676. */
  65677. PostProcess.prototype.getCamera = function () {
  65678. return this._camera;
  65679. };
  65680. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65681. /**
  65682. * Gets the texel size of the postprocess.
  65683. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65684. */
  65685. get: function () {
  65686. if (this._shareOutputWithPostProcess) {
  65687. return this._shareOutputWithPostProcess.texelSize;
  65688. }
  65689. if (this._forcedOutputTexture) {
  65690. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65691. }
  65692. return this._texelSize;
  65693. },
  65694. enumerable: true,
  65695. configurable: true
  65696. });
  65697. /**
  65698. * Gets the engine which this post process belongs to.
  65699. * @returns The engine the post process was enabled with.
  65700. */
  65701. PostProcess.prototype.getEngine = function () {
  65702. return this._engine;
  65703. };
  65704. /**
  65705. * The effect that is created when initializing the post process.
  65706. * @returns The created effect corrisponding the the postprocess.
  65707. */
  65708. PostProcess.prototype.getEffect = function () {
  65709. return this._effect;
  65710. };
  65711. /**
  65712. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65713. * @param postProcess The post process to share the output with.
  65714. * @returns This post process.
  65715. */
  65716. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65717. this._disposeTextures();
  65718. this._shareOutputWithPostProcess = postProcess;
  65719. return this;
  65720. };
  65721. /**
  65722. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65723. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65724. */
  65725. PostProcess.prototype.useOwnOutput = function () {
  65726. if (this._textures.length == 0) {
  65727. this._textures = new BABYLON.SmartArray(2);
  65728. }
  65729. this._shareOutputWithPostProcess = null;
  65730. };
  65731. /**
  65732. * Updates the effect with the current post process compile time values and recompiles the shader.
  65733. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65734. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65735. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65736. * @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
  65737. * @param onCompiled Called when the shader has been compiled.
  65738. * @param onError Called if there is an error when compiling a shader.
  65739. */
  65740. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65741. if (defines === void 0) { defines = null; }
  65742. if (uniforms === void 0) { uniforms = null; }
  65743. if (samplers === void 0) { samplers = null; }
  65744. 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);
  65745. };
  65746. /**
  65747. * The post process is reusable if it can be used multiple times within one frame.
  65748. * @returns If the post process is reusable
  65749. */
  65750. PostProcess.prototype.isReusable = function () {
  65751. return this._reusable;
  65752. };
  65753. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65754. PostProcess.prototype.markTextureDirty = function () {
  65755. this.width = -1;
  65756. };
  65757. /**
  65758. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65759. * 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.
  65760. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65761. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65762. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65763. * @returns The target texture that was bound to be written to.
  65764. */
  65765. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65766. var _this = this;
  65767. if (sourceTexture === void 0) { sourceTexture = null; }
  65768. camera = camera || this._camera;
  65769. var scene = camera.getScene();
  65770. var engine = scene.getEngine();
  65771. var maxSize = engine.getCaps().maxTextureSize;
  65772. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65773. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65774. // 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
  65775. var webVRCamera = camera.parent;
  65776. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65777. requiredWidth /= 2;
  65778. }
  65779. var desiredWidth = (this._options.width || requiredWidth);
  65780. var desiredHeight = this._options.height || requiredHeight;
  65781. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65782. if (this.adaptScaleToCurrentViewport) {
  65783. var currentViewport = engine.currentViewport;
  65784. if (currentViewport) {
  65785. desiredWidth *= currentViewport.width;
  65786. desiredHeight *= currentViewport.height;
  65787. }
  65788. }
  65789. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65790. if (!this._options.width) {
  65791. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65792. }
  65793. if (!this._options.height) {
  65794. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65795. }
  65796. }
  65797. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65798. if (this._textures.length > 0) {
  65799. for (var i = 0; i < this._textures.length; i++) {
  65800. this._engine._releaseTexture(this._textures.data[i]);
  65801. }
  65802. this._textures.reset();
  65803. }
  65804. this.width = desiredWidth;
  65805. this.height = desiredHeight;
  65806. var textureSize = { width: this.width, height: this.height };
  65807. var textureOptions = {
  65808. generateMipMaps: false,
  65809. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65810. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65811. samplingMode: this.renderTargetSamplingMode,
  65812. type: this._textureType
  65813. };
  65814. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65815. if (this._reusable) {
  65816. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65817. }
  65818. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65819. this.onSizeChangedObservable.notifyObservers(this);
  65820. }
  65821. this._textures.forEach(function (texture) {
  65822. if (texture.samples !== _this.samples) {
  65823. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65824. }
  65825. });
  65826. }
  65827. var target;
  65828. if (this._shareOutputWithPostProcess) {
  65829. target = this._shareOutputWithPostProcess.inputTexture;
  65830. }
  65831. else if (this._forcedOutputTexture) {
  65832. target = this._forcedOutputTexture;
  65833. this.width = this._forcedOutputTexture.width;
  65834. this.height = this._forcedOutputTexture.height;
  65835. }
  65836. else {
  65837. target = this.inputTexture;
  65838. }
  65839. // Bind the input of this post process to be used as the output of the previous post process.
  65840. if (this.enablePixelPerfectMode) {
  65841. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65842. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65843. }
  65844. else {
  65845. this._scaleRatio.copyFromFloats(1, 1);
  65846. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65847. }
  65848. this.onActivateObservable.notifyObservers(camera);
  65849. // Clear
  65850. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65851. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65852. }
  65853. if (this._reusable) {
  65854. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65855. }
  65856. return target;
  65857. };
  65858. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65859. /**
  65860. * If the post process is supported.
  65861. */
  65862. get: function () {
  65863. return this._effect.isSupported;
  65864. },
  65865. enumerable: true,
  65866. configurable: true
  65867. });
  65868. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65869. /**
  65870. * The aspect ratio of the output texture.
  65871. */
  65872. get: function () {
  65873. if (this._shareOutputWithPostProcess) {
  65874. return this._shareOutputWithPostProcess.aspectRatio;
  65875. }
  65876. if (this._forcedOutputTexture) {
  65877. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65878. }
  65879. return this.width / this.height;
  65880. },
  65881. enumerable: true,
  65882. configurable: true
  65883. });
  65884. /**
  65885. * Get a value indicating if the post-process is ready to be used
  65886. * @returns true if the post-process is ready (shader is compiled)
  65887. */
  65888. PostProcess.prototype.isReady = function () {
  65889. return this._effect && this._effect.isReady();
  65890. };
  65891. /**
  65892. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65893. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65894. */
  65895. PostProcess.prototype.apply = function () {
  65896. // Check
  65897. if (!this._effect || !this._effect.isReady())
  65898. return null;
  65899. // States
  65900. this._engine.enableEffect(this._effect);
  65901. this._engine.setState(false);
  65902. this._engine.setDepthBuffer(false);
  65903. this._engine.setDepthWrite(false);
  65904. // Alpha
  65905. this._engine.setAlphaMode(this.alphaMode);
  65906. if (this.alphaConstants) {
  65907. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65908. }
  65909. // Bind the output texture of the preivous post process as the input to this post process.
  65910. var source;
  65911. if (this._shareOutputWithPostProcess) {
  65912. source = this._shareOutputWithPostProcess.inputTexture;
  65913. }
  65914. else if (this._forcedOutputTexture) {
  65915. source = this._forcedOutputTexture;
  65916. }
  65917. else {
  65918. source = this.inputTexture;
  65919. }
  65920. this._effect._bindTexture("textureSampler", source);
  65921. // Parameters
  65922. this._effect.setVector2("scale", this._scaleRatio);
  65923. this.onApplyObservable.notifyObservers(this._effect);
  65924. return this._effect;
  65925. };
  65926. PostProcess.prototype._disposeTextures = function () {
  65927. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65928. return;
  65929. }
  65930. if (this._textures.length > 0) {
  65931. for (var i = 0; i < this._textures.length; i++) {
  65932. this._engine._releaseTexture(this._textures.data[i]);
  65933. }
  65934. }
  65935. this._textures.dispose();
  65936. };
  65937. /**
  65938. * Disposes the post process.
  65939. * @param camera The camera to dispose the post process on.
  65940. */
  65941. PostProcess.prototype.dispose = function (camera) {
  65942. camera = camera || this._camera;
  65943. this._disposeTextures();
  65944. if (this._scene) {
  65945. var index_1 = this._scene.postProcesses.indexOf(this);
  65946. if (index_1 !== -1) {
  65947. this._scene.postProcesses.splice(index_1, 1);
  65948. }
  65949. }
  65950. else {
  65951. var index_2 = this._engine.postProcesses.indexOf(this);
  65952. if (index_2 !== -1) {
  65953. this._engine.postProcesses.splice(index_2, 1);
  65954. }
  65955. }
  65956. if (!camera) {
  65957. return;
  65958. }
  65959. camera.detachPostProcess(this);
  65960. var index = camera._postProcesses.indexOf(this);
  65961. if (index === 0 && camera._postProcesses.length > 0) {
  65962. var firstPostProcess = this._camera._getFirstPostProcess();
  65963. if (firstPostProcess) {
  65964. firstPostProcess.markTextureDirty();
  65965. }
  65966. }
  65967. this.onActivateObservable.clear();
  65968. this.onAfterRenderObservable.clear();
  65969. this.onApplyObservable.clear();
  65970. this.onBeforeRenderObservable.clear();
  65971. this.onSizeChangedObservable.clear();
  65972. };
  65973. return PostProcess;
  65974. }());
  65975. BABYLON.PostProcess = PostProcess;
  65976. })(BABYLON || (BABYLON = {}));
  65977. //# sourceMappingURL=babylon.postProcess.js.map
  65978. var BABYLON;
  65979. (function (BABYLON) {
  65980. var PassPostProcess = /** @class */ (function (_super) {
  65981. __extends(PassPostProcess, _super);
  65982. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65983. if (camera === void 0) { camera = null; }
  65984. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65985. if (blockCompilation === void 0) { blockCompilation = false; }
  65986. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65987. }
  65988. return PassPostProcess;
  65989. }(BABYLON.PostProcess));
  65990. BABYLON.PassPostProcess = PassPostProcess;
  65991. })(BABYLON || (BABYLON = {}));
  65992. //# sourceMappingURL=babylon.passPostProcess.js.map
  65993. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65994. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65995. s = arguments[i];
  65996. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65997. t[p] = s[p];
  65998. }
  65999. return t;
  66000. };
  66001. var BABYLON;
  66002. (function (BABYLON) {
  66003. /**
  66004. * Default implementation IShadowGenerator.
  66005. * This is the main object responsible of generating shadows in the framework.
  66006. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66007. */
  66008. var ShadowGenerator = /** @class */ (function () {
  66009. /**
  66010. * Creates a ShadowGenerator object.
  66011. * A ShadowGenerator is the required tool to use the shadows.
  66012. * Each light casting shadows needs to use its own ShadowGenerator.
  66013. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66014. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66015. * @param light The light object generating the shadows.
  66016. * @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.
  66017. */
  66018. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66019. this._bias = 0.00005;
  66020. this._normalBias = 0;
  66021. this._blurBoxOffset = 1;
  66022. this._blurScale = 2;
  66023. this._blurKernel = 1;
  66024. this._useKernelBlur = false;
  66025. this._filter = ShadowGenerator.FILTER_NONE;
  66026. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66027. this._contactHardeningLightSizeUVRatio = 0.1;
  66028. this._darkness = 0;
  66029. this._transparencyShadow = false;
  66030. /**
  66031. * Controls the extent to which the shadows fade out at the edge of the frustum
  66032. * Used only by directionals and spots
  66033. */
  66034. this.frustumEdgeFalloff = 0;
  66035. /**
  66036. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66037. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66038. * It might on the other hand introduce peter panning.
  66039. */
  66040. this.forceBackFacesOnly = false;
  66041. this._lightDirection = BABYLON.Vector3.Zero();
  66042. this._viewMatrix = BABYLON.Matrix.Zero();
  66043. this._projectionMatrix = BABYLON.Matrix.Zero();
  66044. this._transformMatrix = BABYLON.Matrix.Zero();
  66045. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66046. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66047. this._currentFaceIndex = 0;
  66048. this._currentFaceIndexCache = 0;
  66049. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66050. this._mapSize = mapSize;
  66051. this._light = light;
  66052. this._scene = light.getScene();
  66053. light._shadowGenerator = this;
  66054. // Texture type fallback from float to int if not supported.
  66055. var caps = this._scene.getEngine().getCaps();
  66056. if (!useFullFloatFirst) {
  66057. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66058. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66059. }
  66060. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66061. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66062. }
  66063. else {
  66064. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66065. }
  66066. }
  66067. else {
  66068. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66069. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66070. }
  66071. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66072. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66073. }
  66074. else {
  66075. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66076. }
  66077. }
  66078. this._initializeGenerator();
  66079. this._applyFilterValues();
  66080. }
  66081. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66082. /**
  66083. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66084. */
  66085. get: function () {
  66086. return this._bias;
  66087. },
  66088. /**
  66089. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66090. */
  66091. set: function (bias) {
  66092. this._bias = bias;
  66093. },
  66094. enumerable: true,
  66095. configurable: true
  66096. });
  66097. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66098. /**
  66099. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66100. */
  66101. get: function () {
  66102. return this._normalBias;
  66103. },
  66104. /**
  66105. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66106. */
  66107. set: function (normalBias) {
  66108. this._normalBias = normalBias;
  66109. },
  66110. enumerable: true,
  66111. configurable: true
  66112. });
  66113. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66114. /**
  66115. * Gets the blur box offset: offset applied during the blur pass.
  66116. * Only usefull if useKernelBlur = false
  66117. */
  66118. get: function () {
  66119. return this._blurBoxOffset;
  66120. },
  66121. /**
  66122. * Sets the blur box offset: offset applied during the blur pass.
  66123. * Only usefull if useKernelBlur = false
  66124. */
  66125. set: function (value) {
  66126. if (this._blurBoxOffset === value) {
  66127. return;
  66128. }
  66129. this._blurBoxOffset = value;
  66130. this._disposeBlurPostProcesses();
  66131. },
  66132. enumerable: true,
  66133. configurable: true
  66134. });
  66135. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66136. /**
  66137. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66138. * 2 means half of the size.
  66139. */
  66140. get: function () {
  66141. return this._blurScale;
  66142. },
  66143. /**
  66144. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66145. * 2 means half of the size.
  66146. */
  66147. set: function (value) {
  66148. if (this._blurScale === value) {
  66149. return;
  66150. }
  66151. this._blurScale = value;
  66152. this._disposeBlurPostProcesses();
  66153. },
  66154. enumerable: true,
  66155. configurable: true
  66156. });
  66157. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66158. /**
  66159. * Gets the blur kernel: kernel size of the blur pass.
  66160. * Only usefull if useKernelBlur = true
  66161. */
  66162. get: function () {
  66163. return this._blurKernel;
  66164. },
  66165. /**
  66166. * Sets the blur kernel: kernel size of the blur pass.
  66167. * Only usefull if useKernelBlur = true
  66168. */
  66169. set: function (value) {
  66170. if (this._blurKernel === value) {
  66171. return;
  66172. }
  66173. this._blurKernel = value;
  66174. this._disposeBlurPostProcesses();
  66175. },
  66176. enumerable: true,
  66177. configurable: true
  66178. });
  66179. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66180. /**
  66181. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66182. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66183. */
  66184. get: function () {
  66185. return this._useKernelBlur;
  66186. },
  66187. /**
  66188. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66189. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66190. */
  66191. set: function (value) {
  66192. if (this._useKernelBlur === value) {
  66193. return;
  66194. }
  66195. this._useKernelBlur = value;
  66196. this._disposeBlurPostProcesses();
  66197. },
  66198. enumerable: true,
  66199. configurable: true
  66200. });
  66201. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66202. /**
  66203. * Gets the depth scale used in ESM mode.
  66204. */
  66205. get: function () {
  66206. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66207. },
  66208. /**
  66209. * Sets the depth scale used in ESM mode.
  66210. * This can override the scale stored on the light.
  66211. */
  66212. set: function (value) {
  66213. this._depthScale = value;
  66214. },
  66215. enumerable: true,
  66216. configurable: true
  66217. });
  66218. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66219. /**
  66220. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66221. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66222. */
  66223. get: function () {
  66224. return this._filter;
  66225. },
  66226. /**
  66227. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66228. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66229. */
  66230. set: function (value) {
  66231. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66232. if (this._light.needCube()) {
  66233. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66234. this.useExponentialShadowMap = true;
  66235. return;
  66236. }
  66237. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66238. this.useCloseExponentialShadowMap = true;
  66239. return;
  66240. }
  66241. // PCF on cubemap would also be expensive
  66242. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66243. this.usePoissonSampling = true;
  66244. return;
  66245. }
  66246. }
  66247. // Weblg1 fallback for PCF.
  66248. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66249. if (this._scene.getEngine().webGLVersion === 1) {
  66250. this.usePoissonSampling = true;
  66251. return;
  66252. }
  66253. }
  66254. if (this._filter === value) {
  66255. return;
  66256. }
  66257. this._filter = value;
  66258. this._disposeBlurPostProcesses();
  66259. this._applyFilterValues();
  66260. this._light._markMeshesAsLightDirty();
  66261. },
  66262. enumerable: true,
  66263. configurable: true
  66264. });
  66265. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66266. /**
  66267. * Gets if the current filter is set to Poisson Sampling.
  66268. */
  66269. get: function () {
  66270. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66271. },
  66272. /**
  66273. * Sets the current filter to Poisson Sampling.
  66274. */
  66275. set: function (value) {
  66276. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66277. return;
  66278. }
  66279. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66280. },
  66281. enumerable: true,
  66282. configurable: true
  66283. });
  66284. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66285. /**
  66286. * Gets if the current filter is set to VSM.
  66287. * DEPRECATED. Should use useExponentialShadowMap instead.
  66288. */
  66289. get: function () {
  66290. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66291. return this.useExponentialShadowMap;
  66292. },
  66293. /**
  66294. * Sets the current filter is to VSM.
  66295. * DEPRECATED. Should use useExponentialShadowMap instead.
  66296. */
  66297. set: function (value) {
  66298. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66299. this.useExponentialShadowMap = value;
  66300. },
  66301. enumerable: true,
  66302. configurable: true
  66303. });
  66304. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66305. /**
  66306. * Gets if the current filter is set to blurred VSM.
  66307. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66308. */
  66309. get: function () {
  66310. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66311. return this.useBlurExponentialShadowMap;
  66312. },
  66313. /**
  66314. * Sets the current filter is to blurred VSM.
  66315. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66316. */
  66317. set: function (value) {
  66318. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66319. this.useBlurExponentialShadowMap = value;
  66320. },
  66321. enumerable: true,
  66322. configurable: true
  66323. });
  66324. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66325. /**
  66326. * Gets if the current filter is set to ESM.
  66327. */
  66328. get: function () {
  66329. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66330. },
  66331. /**
  66332. * Sets the current filter is to ESM.
  66333. */
  66334. set: function (value) {
  66335. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66336. return;
  66337. }
  66338. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66339. },
  66340. enumerable: true,
  66341. configurable: true
  66342. });
  66343. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66344. /**
  66345. * Gets if the current filter is set to filtered ESM.
  66346. */
  66347. get: function () {
  66348. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66349. },
  66350. /**
  66351. * Gets if the current filter is set to filtered ESM.
  66352. */
  66353. set: function (value) {
  66354. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66355. return;
  66356. }
  66357. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66358. },
  66359. enumerable: true,
  66360. configurable: true
  66361. });
  66362. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66363. /**
  66364. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66365. * exponential to prevent steep falloff artifacts).
  66366. */
  66367. get: function () {
  66368. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66369. },
  66370. /**
  66371. * Sets the current filter to "close ESM" (using the inverse of the
  66372. * exponential to prevent steep falloff artifacts).
  66373. */
  66374. set: function (value) {
  66375. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66376. return;
  66377. }
  66378. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66379. },
  66380. enumerable: true,
  66381. configurable: true
  66382. });
  66383. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66384. /**
  66385. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66386. * exponential to prevent steep falloff artifacts).
  66387. */
  66388. get: function () {
  66389. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66390. },
  66391. /**
  66392. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66393. * exponential to prevent steep falloff artifacts).
  66394. */
  66395. set: function (value) {
  66396. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66397. return;
  66398. }
  66399. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66400. },
  66401. enumerable: true,
  66402. configurable: true
  66403. });
  66404. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66405. /**
  66406. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66407. */
  66408. get: function () {
  66409. return this.filter === ShadowGenerator.FILTER_PCF;
  66410. },
  66411. /**
  66412. * Sets the current filter to "PCF" (percentage closer filtering).
  66413. */
  66414. set: function (value) {
  66415. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66416. return;
  66417. }
  66418. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66419. },
  66420. enumerable: true,
  66421. configurable: true
  66422. });
  66423. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66424. /**
  66425. * Gets the PCF or PCSS Quality.
  66426. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66427. */
  66428. get: function () {
  66429. return this._filteringQuality;
  66430. },
  66431. /**
  66432. * Sets the PCF or PCSS Quality.
  66433. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66434. */
  66435. set: function (filteringQuality) {
  66436. this._filteringQuality = filteringQuality;
  66437. },
  66438. enumerable: true,
  66439. configurable: true
  66440. });
  66441. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66442. /**
  66443. * Gets if the current filter is set to "PCSS" (contact hardening).
  66444. */
  66445. get: function () {
  66446. return this.filter === ShadowGenerator.FILTER_PCSS;
  66447. },
  66448. /**
  66449. * Sets the current filter to "PCSS" (contact hardening).
  66450. */
  66451. set: function (value) {
  66452. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66453. return;
  66454. }
  66455. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66461. /**
  66462. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66463. * Using a ratio helps keeping shape stability independently of the map size.
  66464. *
  66465. * It does not account for the light projection as it was having too much
  66466. * instability during the light setup or during light position changes.
  66467. *
  66468. * Only valid if useContactHardeningShadow is true.
  66469. */
  66470. get: function () {
  66471. return this._contactHardeningLightSizeUVRatio;
  66472. },
  66473. /**
  66474. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66475. * Using a ratio helps keeping shape stability independently of the map size.
  66476. *
  66477. * It does not account for the light projection as it was having too much
  66478. * instability during the light setup or during light position changes.
  66479. *
  66480. * Only valid if useContactHardeningShadow is true.
  66481. */
  66482. set: function (contactHardeningLightSizeUVRatio) {
  66483. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66484. },
  66485. enumerable: true,
  66486. configurable: true
  66487. });
  66488. /**
  66489. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66490. * 0 means strongest and 1 would means no shadow.
  66491. * @returns the darkness.
  66492. */
  66493. ShadowGenerator.prototype.getDarkness = function () {
  66494. return this._darkness;
  66495. };
  66496. /**
  66497. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66498. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66499. * @returns the shadow generator allowing fluent coding.
  66500. */
  66501. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66502. if (darkness >= 1.0)
  66503. this._darkness = 1.0;
  66504. else if (darkness <= 0.0)
  66505. this._darkness = 0.0;
  66506. else
  66507. this._darkness = darkness;
  66508. return this;
  66509. };
  66510. /**
  66511. * Sets the ability to have transparent shadow (boolean).
  66512. * @param transparent True if transparent else False
  66513. * @returns the shadow generator allowing fluent coding
  66514. */
  66515. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66516. this._transparencyShadow = transparent;
  66517. return this;
  66518. };
  66519. /**
  66520. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66521. * @returns The render target texture if present otherwise, null
  66522. */
  66523. ShadowGenerator.prototype.getShadowMap = function () {
  66524. return this._shadowMap;
  66525. };
  66526. /**
  66527. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66528. * @returns The render target texture if the shadow map is present otherwise, null
  66529. */
  66530. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66531. if (this._shadowMap2) {
  66532. return this._shadowMap2;
  66533. }
  66534. return this._shadowMap;
  66535. };
  66536. /**
  66537. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66538. * @param mesh Mesh to add
  66539. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66540. * @returns the Shadow Generator itself
  66541. */
  66542. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66543. if (includeDescendants === void 0) { includeDescendants = true; }
  66544. if (!this._shadowMap) {
  66545. return this;
  66546. }
  66547. if (!this._shadowMap.renderList) {
  66548. this._shadowMap.renderList = [];
  66549. }
  66550. this._shadowMap.renderList.push(mesh);
  66551. if (includeDescendants) {
  66552. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66553. }
  66554. return this;
  66555. var _a;
  66556. };
  66557. /**
  66558. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66559. * @param mesh Mesh to remove
  66560. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66561. * @returns the Shadow Generator itself
  66562. */
  66563. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66564. if (includeDescendants === void 0) { includeDescendants = true; }
  66565. if (!this._shadowMap || !this._shadowMap.renderList) {
  66566. return this;
  66567. }
  66568. var index = this._shadowMap.renderList.indexOf(mesh);
  66569. if (index !== -1) {
  66570. this._shadowMap.renderList.splice(index, 1);
  66571. }
  66572. if (includeDescendants) {
  66573. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66574. var child = _a[_i];
  66575. this.removeShadowCaster(child);
  66576. }
  66577. }
  66578. return this;
  66579. };
  66580. /**
  66581. * Returns the associated light object.
  66582. * @returns the light generating the shadow
  66583. */
  66584. ShadowGenerator.prototype.getLight = function () {
  66585. return this._light;
  66586. };
  66587. ShadowGenerator.prototype._initializeGenerator = function () {
  66588. this._light._markMeshesAsLightDirty();
  66589. this._initializeShadowMap();
  66590. };
  66591. ShadowGenerator.prototype._initializeShadowMap = function () {
  66592. var _this = this;
  66593. // Render target
  66594. var engine = this._scene.getEngine();
  66595. if (engine.webGLVersion > 1) {
  66596. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66597. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66598. }
  66599. else {
  66600. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66601. }
  66602. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66603. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66604. this._shadowMap.anisotropicFilteringLevel = 1;
  66605. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66606. this._shadowMap.renderParticles = false;
  66607. this._shadowMap.ignoreCameraViewport = true;
  66608. // Record Face Index before render.
  66609. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66610. _this._currentFaceIndex = faceIndex;
  66611. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66612. engine.setColorWrite(false);
  66613. }
  66614. });
  66615. // Custom render function.
  66616. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66617. // Blur if required afer render.
  66618. this._shadowMap.onAfterUnbindObservable.add(function () {
  66619. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66620. engine.setColorWrite(true);
  66621. }
  66622. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66623. return;
  66624. }
  66625. var shadowMap = _this.getShadowMapForRendering();
  66626. if (shadowMap) {
  66627. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66628. }
  66629. });
  66630. // Clear according to the chosen filter.
  66631. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66632. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66633. this._shadowMap.onClearObservable.add(function (engine) {
  66634. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66635. engine.clear(clearOne, false, true, false);
  66636. }
  66637. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66638. engine.clear(clearZero, true, true, false);
  66639. }
  66640. else {
  66641. engine.clear(clearOne, true, true, false);
  66642. }
  66643. });
  66644. };
  66645. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66646. var _this = this;
  66647. var engine = this._scene.getEngine();
  66648. var targetSize = this._mapSize / this.blurScale;
  66649. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66650. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66651. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66652. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66653. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66654. }
  66655. if (this.useKernelBlur) {
  66656. 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);
  66657. this._kernelBlurXPostprocess.width = targetSize;
  66658. this._kernelBlurXPostprocess.height = targetSize;
  66659. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66660. effect.setTexture("textureSampler", _this._shadowMap);
  66661. });
  66662. 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);
  66663. this._kernelBlurXPostprocess.autoClear = false;
  66664. this._kernelBlurYPostprocess.autoClear = false;
  66665. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66666. this._kernelBlurXPostprocess.packedFloat = true;
  66667. this._kernelBlurYPostprocess.packedFloat = true;
  66668. }
  66669. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66670. }
  66671. else {
  66672. 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);
  66673. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66674. effect.setFloat2("screenSize", targetSize, targetSize);
  66675. effect.setTexture("textureSampler", _this._shadowMap);
  66676. });
  66677. this._boxBlurPostprocess.autoClear = false;
  66678. this._blurPostProcesses = [this._boxBlurPostprocess];
  66679. }
  66680. };
  66681. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66682. var index;
  66683. var engine = this._scene.getEngine();
  66684. if (depthOnlySubMeshes.length) {
  66685. engine.setColorWrite(false);
  66686. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66687. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66688. }
  66689. engine.setColorWrite(true);
  66690. }
  66691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66692. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66693. }
  66694. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66695. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66696. }
  66697. if (this._transparencyShadow) {
  66698. for (index = 0; index < transparentSubMeshes.length; index++) {
  66699. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66700. }
  66701. }
  66702. };
  66703. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66704. var _this = this;
  66705. var mesh = subMesh.getRenderingMesh();
  66706. var scene = this._scene;
  66707. var engine = scene.getEngine();
  66708. var material = subMesh.getMaterial();
  66709. if (!material) {
  66710. return;
  66711. }
  66712. // Culling
  66713. engine.setState(material.backFaceCulling);
  66714. // Managing instances
  66715. var batch = mesh._getInstancesRenderList(subMesh._id);
  66716. if (batch.mustReturn) {
  66717. return;
  66718. }
  66719. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66720. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66721. engine.enableEffect(this._effect);
  66722. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66723. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66724. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66725. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66726. this._effect.setVector3("lightData", this._cachedDirection);
  66727. }
  66728. else {
  66729. this._effect.setVector3("lightData", this._cachedPosition);
  66730. }
  66731. if (scene.activeCamera) {
  66732. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66733. }
  66734. // Alpha test
  66735. if (material && material.needAlphaTesting()) {
  66736. var alphaTexture = material.getAlphaTestTexture();
  66737. if (alphaTexture) {
  66738. this._effect.setTexture("diffuseSampler", alphaTexture);
  66739. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66740. }
  66741. }
  66742. // Bones
  66743. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66744. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66745. }
  66746. // Morph targets
  66747. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66748. if (this.forceBackFacesOnly) {
  66749. engine.setState(true, 0, false, true);
  66750. }
  66751. // Draw
  66752. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66753. if (this.forceBackFacesOnly) {
  66754. engine.setState(true, 0, false, false);
  66755. }
  66756. }
  66757. else {
  66758. // Need to reset refresh rate of the shadowMap
  66759. if (this._shadowMap) {
  66760. this._shadowMap.resetRefreshCounter();
  66761. }
  66762. }
  66763. };
  66764. ShadowGenerator.prototype._applyFilterValues = function () {
  66765. if (!this._shadowMap) {
  66766. return;
  66767. }
  66768. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66769. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66770. }
  66771. else {
  66772. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66773. }
  66774. };
  66775. /**
  66776. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66777. * @param onCompiled Callback triggered at the and of the effects compilation
  66778. * @param options Sets of optional options forcing the compilation with different modes
  66779. */
  66780. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66781. var _this = this;
  66782. var localOptions = __assign({ useInstances: false }, options);
  66783. var shadowMap = this.getShadowMap();
  66784. if (!shadowMap) {
  66785. if (onCompiled) {
  66786. onCompiled(this);
  66787. }
  66788. return;
  66789. }
  66790. var renderList = shadowMap.renderList;
  66791. if (!renderList) {
  66792. if (onCompiled) {
  66793. onCompiled(this);
  66794. }
  66795. return;
  66796. }
  66797. var subMeshes = new Array();
  66798. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66799. var mesh = renderList_1[_i];
  66800. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66801. }
  66802. if (subMeshes.length === 0) {
  66803. if (onCompiled) {
  66804. onCompiled(this);
  66805. }
  66806. return;
  66807. }
  66808. var currentIndex = 0;
  66809. var checkReady = function () {
  66810. if (!_this._scene || !_this._scene.getEngine()) {
  66811. return;
  66812. }
  66813. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66814. currentIndex++;
  66815. if (currentIndex >= subMeshes.length) {
  66816. if (onCompiled) {
  66817. onCompiled(_this);
  66818. }
  66819. return;
  66820. }
  66821. }
  66822. setTimeout(checkReady, 16);
  66823. };
  66824. checkReady();
  66825. };
  66826. /**
  66827. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66828. * @param options Sets of optional options forcing the compilation with different modes
  66829. * @returns A promise that resolves when the compilation completes
  66830. */
  66831. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66832. var _this = this;
  66833. return new Promise(function (resolve) {
  66834. _this.forceCompilation(function () {
  66835. resolve();
  66836. }, options);
  66837. });
  66838. };
  66839. /**
  66840. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66841. * @param subMesh The submesh we want to render in the shadow map
  66842. * @param useInstances Defines wether will draw in the map using instances
  66843. * @returns true if ready otherwise, false
  66844. */
  66845. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66846. var defines = [];
  66847. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66848. defines.push("#define FLOAT");
  66849. }
  66850. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66851. defines.push("#define ESM");
  66852. }
  66853. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66854. defines.push("#define DEPTHTEXTURE");
  66855. }
  66856. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66857. var mesh = subMesh.getMesh();
  66858. var material = subMesh.getMaterial();
  66859. // Normal bias.
  66860. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66861. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66862. defines.push("#define NORMAL");
  66863. if (mesh.nonUniformScaling) {
  66864. defines.push("#define NONUNIFORMSCALING");
  66865. }
  66866. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66867. defines.push("#define DIRECTIONINLIGHTDATA");
  66868. }
  66869. }
  66870. // Alpha test
  66871. if (material && material.needAlphaTesting()) {
  66872. var alphaTexture = material.getAlphaTestTexture();
  66873. if (alphaTexture) {
  66874. defines.push("#define ALPHATEST");
  66875. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66876. attribs.push(BABYLON.VertexBuffer.UVKind);
  66877. defines.push("#define UV1");
  66878. }
  66879. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66880. if (alphaTexture.coordinatesIndex === 1) {
  66881. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66882. defines.push("#define UV2");
  66883. }
  66884. }
  66885. }
  66886. }
  66887. // Bones
  66888. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66891. if (mesh.numBoneInfluencers > 4) {
  66892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66894. }
  66895. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66896. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66897. }
  66898. else {
  66899. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66900. }
  66901. // Morph targets
  66902. var manager = mesh.morphTargetManager;
  66903. var morphInfluencers = 0;
  66904. if (manager) {
  66905. if (manager.numInfluencers > 0) {
  66906. defines.push("#define MORPHTARGETS");
  66907. morphInfluencers = manager.numInfluencers;
  66908. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66909. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66910. }
  66911. }
  66912. // Instances
  66913. if (useInstances) {
  66914. defines.push("#define INSTANCES");
  66915. attribs.push("world0");
  66916. attribs.push("world1");
  66917. attribs.push("world2");
  66918. attribs.push("world3");
  66919. }
  66920. // Get correct effect
  66921. var join = defines.join("\n");
  66922. if (this._cachedDefines !== join) {
  66923. this._cachedDefines = join;
  66924. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66925. }
  66926. if (!this._effect.isReady()) {
  66927. return false;
  66928. }
  66929. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66930. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66931. this._initializeBlurRTTAndPostProcesses();
  66932. }
  66933. }
  66934. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66935. return false;
  66936. }
  66937. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66938. return false;
  66939. }
  66940. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66941. return false;
  66942. }
  66943. return true;
  66944. };
  66945. /**
  66946. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66947. * @param defines Defines of the material we want to update
  66948. * @param lightIndex Index of the light in the enabled light list of the material
  66949. */
  66950. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66951. var scene = this._scene;
  66952. var light = this._light;
  66953. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66954. return;
  66955. }
  66956. defines["SHADOW" + lightIndex] = true;
  66957. if (this.useContactHardeningShadow) {
  66958. defines["SHADOWPCSS" + lightIndex] = true;
  66959. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66960. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66961. }
  66962. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66963. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66964. }
  66965. // else default to high.
  66966. }
  66967. if (this.usePercentageCloserFiltering) {
  66968. defines["SHADOWPCF" + lightIndex] = true;
  66969. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66970. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66971. }
  66972. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66973. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66974. }
  66975. // else default to high.
  66976. }
  66977. else if (this.usePoissonSampling) {
  66978. defines["SHADOWPOISSON" + lightIndex] = true;
  66979. }
  66980. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66981. defines["SHADOWESM" + lightIndex] = true;
  66982. }
  66983. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66984. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66985. }
  66986. if (light.needCube()) {
  66987. defines["SHADOWCUBE" + lightIndex] = true;
  66988. }
  66989. };
  66990. /**
  66991. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66992. * defined in the generator but impacting the effect).
  66993. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66994. * @param effect The effect we are binfing the information for
  66995. */
  66996. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66997. var light = this._light;
  66998. var scene = this._scene;
  66999. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67000. return;
  67001. }
  67002. var camera = scene.activeCamera;
  67003. if (!camera) {
  67004. return;
  67005. }
  67006. var shadowMap = this.getShadowMap();
  67007. if (!shadowMap) {
  67008. return;
  67009. }
  67010. if (!light.needCube()) {
  67011. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67012. }
  67013. // Only PCF uses depth stencil texture.
  67014. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67015. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67016. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67017. }
  67018. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67019. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67020. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67021. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67022. }
  67023. else {
  67024. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67025. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67026. }
  67027. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67028. };
  67029. /**
  67030. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67031. * (eq to shadow prjection matrix * light transform matrix)
  67032. * @returns The transform matrix used to create the shadow map
  67033. */
  67034. ShadowGenerator.prototype.getTransformMatrix = function () {
  67035. var scene = this._scene;
  67036. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67037. return this._transformMatrix;
  67038. }
  67039. this._currentRenderID = scene.getRenderId();
  67040. this._currentFaceIndexCache = this._currentFaceIndex;
  67041. var lightPosition = this._light.position;
  67042. if (this._light.computeTransformedInformation()) {
  67043. lightPosition = this._light.transformedPosition;
  67044. }
  67045. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67046. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67047. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67048. }
  67049. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67050. this._cachedPosition.copyFrom(lightPosition);
  67051. this._cachedDirection.copyFrom(this._lightDirection);
  67052. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67053. var shadowMap = this.getShadowMap();
  67054. if (shadowMap) {
  67055. var renderList = shadowMap.renderList;
  67056. if (renderList) {
  67057. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67058. }
  67059. }
  67060. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67061. }
  67062. return this._transformMatrix;
  67063. };
  67064. /**
  67065. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67066. * Cube and 2D textures for instance.
  67067. */
  67068. ShadowGenerator.prototype.recreateShadowMap = function () {
  67069. var shadowMap = this._shadowMap;
  67070. if (!shadowMap) {
  67071. return;
  67072. }
  67073. // Track render list.
  67074. var renderList = shadowMap.renderList;
  67075. // Clean up existing data.
  67076. this._disposeRTTandPostProcesses();
  67077. // Reinitializes.
  67078. this._initializeGenerator();
  67079. // Reaffect the filter to ensure a correct fallback if necessary.
  67080. this.filter = this.filter;
  67081. // Reaffect the filter.
  67082. this._applyFilterValues();
  67083. // Reaffect Render List.
  67084. this._shadowMap.renderList = renderList;
  67085. };
  67086. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67087. if (this._shadowMap2) {
  67088. this._shadowMap2.dispose();
  67089. this._shadowMap2 = null;
  67090. }
  67091. if (this._boxBlurPostprocess) {
  67092. this._boxBlurPostprocess.dispose();
  67093. this._boxBlurPostprocess = null;
  67094. }
  67095. if (this._kernelBlurXPostprocess) {
  67096. this._kernelBlurXPostprocess.dispose();
  67097. this._kernelBlurXPostprocess = null;
  67098. }
  67099. if (this._kernelBlurYPostprocess) {
  67100. this._kernelBlurYPostprocess.dispose();
  67101. this._kernelBlurYPostprocess = null;
  67102. }
  67103. this._blurPostProcesses = [];
  67104. };
  67105. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67106. if (this._shadowMap) {
  67107. this._shadowMap.dispose();
  67108. this._shadowMap = null;
  67109. }
  67110. this._disposeBlurPostProcesses();
  67111. };
  67112. /**
  67113. * Disposes the ShadowGenerator.
  67114. * Returns nothing.
  67115. */
  67116. ShadowGenerator.prototype.dispose = function () {
  67117. this._disposeRTTandPostProcesses();
  67118. if (this._light) {
  67119. this._light._shadowGenerator = null;
  67120. this._light._markMeshesAsLightDirty();
  67121. }
  67122. };
  67123. /**
  67124. * Serializes the shadow generator setup to a json object.
  67125. * @returns The serialized JSON object
  67126. */
  67127. ShadowGenerator.prototype.serialize = function () {
  67128. var serializationObject = {};
  67129. var shadowMap = this.getShadowMap();
  67130. if (!shadowMap) {
  67131. return serializationObject;
  67132. }
  67133. serializationObject.lightId = this._light.id;
  67134. serializationObject.mapSize = shadowMap.getRenderSize();
  67135. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67136. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67137. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67138. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67139. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67140. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67141. serializationObject.depthScale = this.depthScale;
  67142. serializationObject.darkness = this.getDarkness();
  67143. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67144. serializationObject.blurKernel = this.blurKernel;
  67145. serializationObject.blurScale = this.blurScale;
  67146. serializationObject.useKernelBlur = this.useKernelBlur;
  67147. serializationObject.transparencyShadow = this._transparencyShadow;
  67148. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67149. serializationObject.bias = this.bias;
  67150. serializationObject.normalBias = this.normalBias;
  67151. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67152. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67153. serializationObject.filteringQuality = this.filteringQuality;
  67154. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67155. serializationObject.renderList = [];
  67156. if (shadowMap.renderList) {
  67157. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67158. var mesh = shadowMap.renderList[meshIndex];
  67159. serializationObject.renderList.push(mesh.id);
  67160. }
  67161. }
  67162. return serializationObject;
  67163. };
  67164. /**
  67165. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67166. * @param parsedShadowGenerator The JSON object to parse
  67167. * @param scene The scene to create the shadow map for
  67168. * @returns The parsed shadow generator
  67169. */
  67170. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67171. //casting to point light, as light is missing the position attr and typescript complains.
  67172. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67173. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67174. var shadowMap = shadowGenerator.getShadowMap();
  67175. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67176. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67177. meshes.forEach(function (mesh) {
  67178. if (!shadowMap) {
  67179. return;
  67180. }
  67181. if (!shadowMap.renderList) {
  67182. shadowMap.renderList = [];
  67183. }
  67184. shadowMap.renderList.push(mesh);
  67185. });
  67186. }
  67187. if (parsedShadowGenerator.usePoissonSampling) {
  67188. shadowGenerator.usePoissonSampling = true;
  67189. }
  67190. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67191. shadowGenerator.useExponentialShadowMap = true;
  67192. }
  67193. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67194. shadowGenerator.useBlurExponentialShadowMap = true;
  67195. }
  67196. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67197. shadowGenerator.useCloseExponentialShadowMap = true;
  67198. }
  67199. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67200. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67201. }
  67202. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67203. shadowGenerator.usePercentageCloserFiltering = true;
  67204. }
  67205. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67206. shadowGenerator.useContactHardeningShadow = true;
  67207. }
  67208. if (parsedShadowGenerator.filteringQuality) {
  67209. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67210. }
  67211. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67212. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67213. }
  67214. // Backward compat
  67215. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67216. shadowGenerator.useExponentialShadowMap = true;
  67217. }
  67218. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67219. shadowGenerator.useBlurExponentialShadowMap = true;
  67220. }
  67221. if (parsedShadowGenerator.depthScale) {
  67222. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67223. }
  67224. if (parsedShadowGenerator.blurScale) {
  67225. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67226. }
  67227. if (parsedShadowGenerator.blurBoxOffset) {
  67228. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67229. }
  67230. if (parsedShadowGenerator.useKernelBlur) {
  67231. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67232. }
  67233. if (parsedShadowGenerator.blurKernel) {
  67234. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67235. }
  67236. if (parsedShadowGenerator.bias !== undefined) {
  67237. shadowGenerator.bias = parsedShadowGenerator.bias;
  67238. }
  67239. if (parsedShadowGenerator.normalBias !== undefined) {
  67240. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67241. }
  67242. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67243. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67244. }
  67245. if (parsedShadowGenerator.darkness) {
  67246. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67247. }
  67248. if (parsedShadowGenerator.transparencyShadow) {
  67249. shadowGenerator.setTransparencyShadow(true);
  67250. }
  67251. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67252. return shadowGenerator;
  67253. };
  67254. /**
  67255. * Shadow generator mode None: no filtering applied.
  67256. */
  67257. ShadowGenerator.FILTER_NONE = 0;
  67258. /**
  67259. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67260. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67261. */
  67262. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67263. /**
  67264. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67265. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67266. */
  67267. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67268. /**
  67269. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67270. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67271. */
  67272. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67273. /**
  67274. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67275. * edge artifacts on steep falloff.
  67276. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67277. */
  67278. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67279. /**
  67280. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67281. * edge artifacts on steep falloff.
  67282. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67283. */
  67284. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67285. /**
  67286. * Shadow generator mode PCF: Percentage Closer Filtering
  67287. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67288. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67289. */
  67290. ShadowGenerator.FILTER_PCF = 6;
  67291. /**
  67292. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67293. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67294. * Contact Hardening
  67295. */
  67296. ShadowGenerator.FILTER_PCSS = 7;
  67297. /**
  67298. * Reserved for PCF and PCSS
  67299. * Highest Quality.
  67300. *
  67301. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67302. *
  67303. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67304. */
  67305. ShadowGenerator.QUALITY_HIGH = 0;
  67306. /**
  67307. * Reserved for PCF and PCSS
  67308. * Good tradeoff for quality/perf cross devices
  67309. *
  67310. * Execute PCF on a 3*3 kernel.
  67311. *
  67312. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67313. */
  67314. ShadowGenerator.QUALITY_MEDIUM = 1;
  67315. /**
  67316. * Reserved for PCF and PCSS
  67317. * The lowest quality but the fastest.
  67318. *
  67319. * Execute PCF on a 1*1 kernel.
  67320. *
  67321. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67322. */
  67323. ShadowGenerator.QUALITY_LOW = 2;
  67324. return ShadowGenerator;
  67325. }());
  67326. BABYLON.ShadowGenerator = ShadowGenerator;
  67327. })(BABYLON || (BABYLON = {}));
  67328. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67329. var BABYLON;
  67330. (function (BABYLON) {
  67331. var DefaultLoadingScreen = /** @class */ (function () {
  67332. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67333. if (_loadingText === void 0) { _loadingText = ""; }
  67334. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67335. var _this = this;
  67336. this._renderingCanvas = _renderingCanvas;
  67337. this._loadingText = _loadingText;
  67338. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67339. // Resize
  67340. this._resizeLoadingUI = function () {
  67341. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67342. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67343. if (!_this._loadingDiv) {
  67344. return;
  67345. }
  67346. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67347. _this._loadingDiv.style.left = canvasRect.left + "px";
  67348. _this._loadingDiv.style.top = canvasRect.top + "px";
  67349. _this._loadingDiv.style.width = canvasRect.width + "px";
  67350. _this._loadingDiv.style.height = canvasRect.height + "px";
  67351. };
  67352. }
  67353. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67354. if (this._loadingDiv) {
  67355. // Do not add a loading screen if there is already one
  67356. return;
  67357. }
  67358. this._loadingDiv = document.createElement("div");
  67359. this._loadingDiv.id = "babylonjsLoadingDiv";
  67360. this._loadingDiv.style.opacity = "0";
  67361. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67362. this._loadingDiv.style.pointerEvents = "none";
  67363. // Loading text
  67364. this._loadingTextDiv = document.createElement("div");
  67365. this._loadingTextDiv.style.position = "absolute";
  67366. this._loadingTextDiv.style.left = "0";
  67367. this._loadingTextDiv.style.top = "50%";
  67368. this._loadingTextDiv.style.marginTop = "80px";
  67369. this._loadingTextDiv.style.width = "100%";
  67370. this._loadingTextDiv.style.height = "20px";
  67371. this._loadingTextDiv.style.fontFamily = "Arial";
  67372. this._loadingTextDiv.style.fontSize = "14px";
  67373. this._loadingTextDiv.style.color = "white";
  67374. this._loadingTextDiv.style.textAlign = "center";
  67375. this._loadingTextDiv.innerHTML = "Loading";
  67376. this._loadingDiv.appendChild(this._loadingTextDiv);
  67377. //set the predefined text
  67378. this._loadingTextDiv.innerHTML = this._loadingText;
  67379. // Generating keyframes
  67380. var style = document.createElement('style');
  67381. style.type = 'text/css';
  67382. 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 }";
  67383. style.innerHTML = keyFrames;
  67384. document.getElementsByTagName('head')[0].appendChild(style);
  67385. // Loading img
  67386. var imgBack = new Image();
  67387. 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";
  67388. imgBack.style.position = "absolute";
  67389. imgBack.style.left = "50%";
  67390. imgBack.style.top = "50%";
  67391. imgBack.style.marginLeft = "-60px";
  67392. imgBack.style.marginTop = "-60px";
  67393. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67394. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67395. imgBack.style.transformOrigin = "50% 50%";
  67396. imgBack.style.webkitTransformOrigin = "50% 50%";
  67397. this._loadingDiv.appendChild(imgBack);
  67398. this._resizeLoadingUI();
  67399. window.addEventListener("resize", this._resizeLoadingUI);
  67400. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67401. document.body.appendChild(this._loadingDiv);
  67402. this._loadingDiv.style.opacity = "1";
  67403. };
  67404. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67405. var _this = this;
  67406. if (!this._loadingDiv) {
  67407. return;
  67408. }
  67409. var onTransitionEnd = function () {
  67410. if (!_this._loadingDiv) {
  67411. return;
  67412. }
  67413. document.body.removeChild(_this._loadingDiv);
  67414. window.removeEventListener("resize", _this._resizeLoadingUI);
  67415. _this._loadingDiv = null;
  67416. };
  67417. this._loadingDiv.style.opacity = "0";
  67418. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67419. };
  67420. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67421. set: function (text) {
  67422. this._loadingText = text;
  67423. if (this._loadingTextDiv) {
  67424. this._loadingTextDiv.innerHTML = this._loadingText;
  67425. }
  67426. },
  67427. enumerable: true,
  67428. configurable: true
  67429. });
  67430. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67431. get: function () {
  67432. return this._loadingDivBackgroundColor;
  67433. },
  67434. set: function (color) {
  67435. this._loadingDivBackgroundColor = color;
  67436. if (!this._loadingDiv) {
  67437. return;
  67438. }
  67439. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67440. },
  67441. enumerable: true,
  67442. configurable: true
  67443. });
  67444. return DefaultLoadingScreen;
  67445. }());
  67446. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67447. })(BABYLON || (BABYLON = {}));
  67448. //# sourceMappingURL=babylon.loadingScreen.js.map
  67449. var BABYLON;
  67450. (function (BABYLON) {
  67451. var SceneLoaderProgressEvent = /** @class */ (function () {
  67452. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67453. this.lengthComputable = lengthComputable;
  67454. this.loaded = loaded;
  67455. this.total = total;
  67456. }
  67457. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67458. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67459. };
  67460. return SceneLoaderProgressEvent;
  67461. }());
  67462. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67463. var SceneLoader = /** @class */ (function () {
  67464. function SceneLoader() {
  67465. }
  67466. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67467. get: function () {
  67468. return 0;
  67469. },
  67470. enumerable: true,
  67471. configurable: true
  67472. });
  67473. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67474. get: function () {
  67475. return 1;
  67476. },
  67477. enumerable: true,
  67478. configurable: true
  67479. });
  67480. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67481. get: function () {
  67482. return 2;
  67483. },
  67484. enumerable: true,
  67485. configurable: true
  67486. });
  67487. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67488. get: function () {
  67489. return 3;
  67490. },
  67491. enumerable: true,
  67492. configurable: true
  67493. });
  67494. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67495. get: function () {
  67496. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67497. },
  67498. set: function (value) {
  67499. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67500. },
  67501. enumerable: true,
  67502. configurable: true
  67503. });
  67504. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67505. get: function () {
  67506. return SceneLoader._ShowLoadingScreen;
  67507. },
  67508. set: function (value) {
  67509. SceneLoader._ShowLoadingScreen = value;
  67510. },
  67511. enumerable: true,
  67512. configurable: true
  67513. });
  67514. Object.defineProperty(SceneLoader, "loggingLevel", {
  67515. get: function () {
  67516. return SceneLoader._loggingLevel;
  67517. },
  67518. set: function (value) {
  67519. SceneLoader._loggingLevel = value;
  67520. },
  67521. enumerable: true,
  67522. configurable: true
  67523. });
  67524. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67525. get: function () {
  67526. return SceneLoader._CleanBoneMatrixWeights;
  67527. },
  67528. set: function (value) {
  67529. SceneLoader._CleanBoneMatrixWeights = value;
  67530. },
  67531. enumerable: true,
  67532. configurable: true
  67533. });
  67534. SceneLoader._getDefaultPlugin = function () {
  67535. return SceneLoader._registeredPlugins[".babylon"];
  67536. };
  67537. SceneLoader._getPluginForExtension = function (extension) {
  67538. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67539. if (registeredPlugin) {
  67540. return registeredPlugin;
  67541. }
  67542. 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");
  67543. return SceneLoader._getDefaultPlugin();
  67544. };
  67545. SceneLoader._getPluginForDirectLoad = function (data) {
  67546. for (var extension in SceneLoader._registeredPlugins) {
  67547. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67548. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67549. return SceneLoader._registeredPlugins[extension];
  67550. }
  67551. }
  67552. return SceneLoader._getDefaultPlugin();
  67553. };
  67554. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67555. if (sceneFilename.name) {
  67556. sceneFilename = sceneFilename.name;
  67557. }
  67558. var queryStringPosition = sceneFilename.indexOf("?");
  67559. if (queryStringPosition !== -1) {
  67560. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67561. }
  67562. var dotPosition = sceneFilename.lastIndexOf(".");
  67563. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67564. return SceneLoader._getPluginForExtension(extension);
  67565. };
  67566. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67567. SceneLoader._getDirectLoad = function (sceneFilename) {
  67568. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67569. return sceneFilename.substr(5);
  67570. }
  67571. return null;
  67572. };
  67573. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67574. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67575. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67576. var plugin;
  67577. if (registeredPlugin.plugin.createPlugin) {
  67578. plugin = registeredPlugin.plugin.createPlugin();
  67579. }
  67580. else {
  67581. plugin = registeredPlugin.plugin;
  67582. }
  67583. var useArrayBuffer = registeredPlugin.isBinary;
  67584. var database;
  67585. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67586. var dataCallback = function (data, responseURL) {
  67587. if (scene.isDisposed) {
  67588. onError("Scene has been disposed");
  67589. return;
  67590. }
  67591. scene.database = database;
  67592. onSuccess(plugin, data, responseURL);
  67593. };
  67594. var request = null;
  67595. var pluginDisposed = false;
  67596. var onDisposeObservable = plugin.onDisposeObservable;
  67597. if (onDisposeObservable) {
  67598. onDisposeObservable.add(function () {
  67599. pluginDisposed = true;
  67600. if (request) {
  67601. request.abort();
  67602. request = null;
  67603. }
  67604. onDispose();
  67605. });
  67606. }
  67607. var manifestChecked = function () {
  67608. if (pluginDisposed) {
  67609. return;
  67610. }
  67611. var url = rootUrl + sceneFilename;
  67612. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67613. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67614. } : undefined, database, useArrayBuffer, function (request, exception) {
  67615. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67616. });
  67617. };
  67618. if (directLoad) {
  67619. dataCallback(directLoad);
  67620. return plugin;
  67621. }
  67622. if (rootUrl.indexOf("file:") === -1) {
  67623. var engine = scene.getEngine();
  67624. var canUseOfflineSupport = engine.enableOfflineSupport;
  67625. if (canUseOfflineSupport) {
  67626. // Also check for exceptions
  67627. var exceptionFound = false;
  67628. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67629. var regex = _a[_i];
  67630. if (regex.test(rootUrl + sceneFilename)) {
  67631. exceptionFound = true;
  67632. break;
  67633. }
  67634. }
  67635. canUseOfflineSupport = !exceptionFound;
  67636. }
  67637. if (canUseOfflineSupport) {
  67638. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67639. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67640. }
  67641. else {
  67642. manifestChecked();
  67643. }
  67644. }
  67645. // Loading file from disk via input file or drag'n'drop
  67646. else {
  67647. var fileOrString = sceneFilename;
  67648. if (fileOrString.name) { // File
  67649. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67650. }
  67651. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67652. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67653. }
  67654. else {
  67655. onError("Unable to find file named " + sceneFilename);
  67656. }
  67657. }
  67658. return plugin;
  67659. };
  67660. // Public functions
  67661. SceneLoader.GetPluginForExtension = function (extension) {
  67662. return SceneLoader._getPluginForExtension(extension).plugin;
  67663. };
  67664. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67665. return !!SceneLoader._registeredPlugins[extension];
  67666. };
  67667. SceneLoader.RegisterPlugin = function (plugin) {
  67668. if (typeof plugin.extensions === "string") {
  67669. var extension = plugin.extensions;
  67670. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67671. plugin: plugin,
  67672. isBinary: false
  67673. };
  67674. }
  67675. else {
  67676. var extensions = plugin.extensions;
  67677. Object.keys(extensions).forEach(function (extension) {
  67678. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67679. plugin: plugin,
  67680. isBinary: extensions[extension].isBinary
  67681. };
  67682. });
  67683. }
  67684. };
  67685. /**
  67686. * Import meshes into a scene
  67687. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67688. * @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)
  67689. * @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)
  67690. * @param scene the instance of BABYLON.Scene to append to
  67691. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67692. * @param onProgress a callback with a progress event for each file being loaded
  67693. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67694. * @param pluginExtension the extension used to determine the plugin
  67695. * @returns The loaded plugin
  67696. */
  67697. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67698. if (sceneFilename === void 0) { sceneFilename = ""; }
  67699. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67700. if (onSuccess === void 0) { onSuccess = null; }
  67701. if (onProgress === void 0) { onProgress = null; }
  67702. if (onError === void 0) { onError = null; }
  67703. if (pluginExtension === void 0) { pluginExtension = null; }
  67704. if (!scene) {
  67705. BABYLON.Tools.Error("No scene available to import mesh to");
  67706. return null;
  67707. }
  67708. if (!sceneFilename) {
  67709. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67710. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67711. }
  67712. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67713. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67714. return null;
  67715. }
  67716. var loadingToken = {};
  67717. scene._addPendingData(loadingToken);
  67718. var disposeHandler = function () {
  67719. scene._removePendingData(loadingToken);
  67720. };
  67721. var errorHandler = function (message, exception) {
  67722. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67723. if (onError) {
  67724. onError(scene, errorMessage, exception);
  67725. }
  67726. else {
  67727. BABYLON.Tools.Error(errorMessage);
  67728. // should the exception be thrown?
  67729. }
  67730. disposeHandler();
  67731. };
  67732. var progressHandler = onProgress ? function (event) {
  67733. try {
  67734. onProgress(event);
  67735. }
  67736. catch (e) {
  67737. errorHandler("Error in onProgress callback", e);
  67738. }
  67739. } : undefined;
  67740. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67741. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67742. if (onSuccess) {
  67743. try {
  67744. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67745. }
  67746. catch (e) {
  67747. errorHandler("Error in onSuccess callback", e);
  67748. }
  67749. }
  67750. scene._removePendingData(loadingToken);
  67751. };
  67752. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67753. if (plugin.rewriteRootURL) {
  67754. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67755. }
  67756. if (sceneFilename === "") {
  67757. if (sceneFilename === "") {
  67758. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67759. }
  67760. }
  67761. if (plugin.importMesh) {
  67762. var syncedPlugin = plugin;
  67763. var meshes = new Array();
  67764. var particleSystems = new Array();
  67765. var skeletons = new Array();
  67766. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67767. return;
  67768. }
  67769. scene.loadingPluginName = plugin.name;
  67770. successHandler(meshes, particleSystems, skeletons, []);
  67771. }
  67772. else {
  67773. var asyncedPlugin = plugin;
  67774. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67775. scene.loadingPluginName = plugin.name;
  67776. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67777. }).catch(function (error) {
  67778. errorHandler(error.message, error);
  67779. });
  67780. }
  67781. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67782. };
  67783. /**
  67784. * Import meshes into a scene
  67785. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67786. * @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)
  67787. * @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)
  67788. * @param scene the instance of BABYLON.Scene to append to
  67789. * @param onProgress a callback with a progress event for each file being loaded
  67790. * @param pluginExtension the extension used to determine the plugin
  67791. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67792. */
  67793. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67794. if (sceneFilename === void 0) { sceneFilename = ""; }
  67795. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67796. if (onProgress === void 0) { onProgress = null; }
  67797. if (pluginExtension === void 0) { pluginExtension = null; }
  67798. return new Promise(function (resolve, reject) {
  67799. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67800. resolve({
  67801. meshes: meshes,
  67802. particleSystems: particleSystems,
  67803. skeletons: skeletons,
  67804. animationGroups: animationGroups
  67805. });
  67806. }, onProgress, function (scene, message, exception) {
  67807. reject(exception || new Error(message));
  67808. }, pluginExtension);
  67809. });
  67810. };
  67811. /**
  67812. * Load a scene
  67813. * @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)
  67814. * @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)
  67815. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67816. * @param onSuccess a callback with the scene when import succeeds
  67817. * @param onProgress a callback with a progress event for each file being loaded
  67818. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67819. * @param pluginExtension the extension used to determine the plugin
  67820. * @returns The loaded plugin
  67821. */
  67822. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67823. if (onSuccess === void 0) { onSuccess = null; }
  67824. if (onProgress === void 0) { onProgress = null; }
  67825. if (onError === void 0) { onError = null; }
  67826. if (pluginExtension === void 0) { pluginExtension = null; }
  67827. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67828. };
  67829. /**
  67830. * Load a scene
  67831. * @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)
  67832. * @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)
  67833. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67834. * @param onProgress a callback with a progress event for each file being loaded
  67835. * @param pluginExtension the extension used to determine the plugin
  67836. * @returns The loaded scene
  67837. */
  67838. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67839. if (onProgress === void 0) { onProgress = null; }
  67840. if (pluginExtension === void 0) { pluginExtension = null; }
  67841. return new Promise(function (resolve, reject) {
  67842. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67843. resolve(scene);
  67844. }, onProgress, function (scene, message, exception) {
  67845. reject(exception || new Error(message));
  67846. }, pluginExtension);
  67847. });
  67848. };
  67849. /**
  67850. * Append a scene
  67851. * @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)
  67852. * @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)
  67853. * @param scene is the instance of BABYLON.Scene to append to
  67854. * @param onSuccess a callback with the scene when import succeeds
  67855. * @param onProgress a callback with a progress event for each file being loaded
  67856. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67857. * @param pluginExtension the extension used to determine the plugin
  67858. * @returns The loaded plugin
  67859. */
  67860. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67861. if (sceneFilename === void 0) { sceneFilename = ""; }
  67862. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67863. if (onSuccess === void 0) { onSuccess = null; }
  67864. if (onProgress === void 0) { onProgress = null; }
  67865. if (onError === void 0) { onError = null; }
  67866. if (pluginExtension === void 0) { pluginExtension = null; }
  67867. if (!scene) {
  67868. BABYLON.Tools.Error("No scene available to append to");
  67869. return null;
  67870. }
  67871. if (!sceneFilename) {
  67872. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67873. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67874. }
  67875. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67876. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67877. return null;
  67878. }
  67879. if (SceneLoader.ShowLoadingScreen) {
  67880. scene.getEngine().displayLoadingUI();
  67881. }
  67882. var loadingToken = {};
  67883. scene._addPendingData(loadingToken);
  67884. var disposeHandler = function () {
  67885. scene._removePendingData(loadingToken);
  67886. scene.getEngine().hideLoadingUI();
  67887. };
  67888. var errorHandler = function (message, exception) {
  67889. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67890. if (onError) {
  67891. onError(scene, errorMessage, exception);
  67892. }
  67893. else {
  67894. BABYLON.Tools.Error(errorMessage);
  67895. // should the exception be thrown?
  67896. }
  67897. disposeHandler();
  67898. };
  67899. var progressHandler = onProgress ? function (event) {
  67900. try {
  67901. onProgress(event);
  67902. }
  67903. catch (e) {
  67904. errorHandler("Error in onProgress callback", e);
  67905. }
  67906. } : undefined;
  67907. var successHandler = function () {
  67908. if (onSuccess) {
  67909. try {
  67910. onSuccess(scene);
  67911. }
  67912. catch (e) {
  67913. errorHandler("Error in onSuccess callback", e);
  67914. }
  67915. }
  67916. scene._removePendingData(loadingToken);
  67917. };
  67918. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67919. if (sceneFilename === "") {
  67920. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67921. }
  67922. if (plugin.load) {
  67923. var syncedPlugin = plugin;
  67924. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67925. return;
  67926. }
  67927. scene.loadingPluginName = plugin.name;
  67928. successHandler();
  67929. }
  67930. else {
  67931. var asyncedPlugin = plugin;
  67932. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67933. scene.loadingPluginName = plugin.name;
  67934. successHandler();
  67935. }).catch(function (error) {
  67936. errorHandler(error.message, error);
  67937. });
  67938. }
  67939. if (SceneLoader.ShowLoadingScreen) {
  67940. scene.executeWhenReady(function () {
  67941. scene.getEngine().hideLoadingUI();
  67942. });
  67943. }
  67944. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67945. };
  67946. /**
  67947. * Append a scene
  67948. * @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)
  67949. * @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)
  67950. * @param scene is the instance of BABYLON.Scene to append to
  67951. * @param onProgress a callback with a progress event for each file being loaded
  67952. * @param pluginExtension the extension used to determine the plugin
  67953. * @returns The given scene
  67954. */
  67955. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67956. if (sceneFilename === void 0) { sceneFilename = ""; }
  67957. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67958. if (onProgress === void 0) { onProgress = null; }
  67959. if (pluginExtension === void 0) { pluginExtension = null; }
  67960. return new Promise(function (resolve, reject) {
  67961. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67962. resolve(scene);
  67963. }, onProgress, function (scene, message, exception) {
  67964. reject(exception || new Error(message));
  67965. }, pluginExtension);
  67966. });
  67967. };
  67968. /**
  67969. * Load a scene into an asset container
  67970. * @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)
  67971. * @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)
  67972. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67973. * @param onSuccess a callback with the scene when import succeeds
  67974. * @param onProgress a callback with a progress event for each file being loaded
  67975. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67976. * @param pluginExtension the extension used to determine the plugin
  67977. * @returns The loaded plugin
  67978. */
  67979. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67980. if (sceneFilename === void 0) { sceneFilename = ""; }
  67981. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67982. if (onSuccess === void 0) { onSuccess = null; }
  67983. if (onProgress === void 0) { onProgress = null; }
  67984. if (onError === void 0) { onError = null; }
  67985. if (pluginExtension === void 0) { pluginExtension = null; }
  67986. if (!scene) {
  67987. BABYLON.Tools.Error("No scene available to load asset container to");
  67988. return null;
  67989. }
  67990. if (!sceneFilename) {
  67991. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67992. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67993. }
  67994. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67995. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67996. return null;
  67997. }
  67998. var loadingToken = {};
  67999. scene._addPendingData(loadingToken);
  68000. var disposeHandler = function () {
  68001. scene._removePendingData(loadingToken);
  68002. };
  68003. var errorHandler = function (message, exception) {
  68004. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68005. if (onError) {
  68006. onError(scene, errorMessage, exception);
  68007. }
  68008. else {
  68009. BABYLON.Tools.Error(errorMessage);
  68010. // should the exception be thrown?
  68011. }
  68012. disposeHandler();
  68013. };
  68014. var progressHandler = onProgress ? function (event) {
  68015. try {
  68016. onProgress(event);
  68017. }
  68018. catch (e) {
  68019. errorHandler("Error in onProgress callback", e);
  68020. }
  68021. } : undefined;
  68022. var successHandler = function (assets) {
  68023. if (onSuccess) {
  68024. try {
  68025. onSuccess(assets);
  68026. }
  68027. catch (e) {
  68028. errorHandler("Error in onSuccess callback", e);
  68029. }
  68030. }
  68031. scene._removePendingData(loadingToken);
  68032. };
  68033. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68034. if (plugin.loadAssetContainer) {
  68035. var syncedPlugin = plugin;
  68036. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68037. if (!assetContainer) {
  68038. return;
  68039. }
  68040. scene.loadingPluginName = plugin.name;
  68041. successHandler(assetContainer);
  68042. }
  68043. else if (plugin.loadAssetContainerAsync) {
  68044. var asyncedPlugin = plugin;
  68045. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68046. scene.loadingPluginName = plugin.name;
  68047. successHandler(assetContainer);
  68048. }).catch(function (error) {
  68049. errorHandler(error.message, error);
  68050. });
  68051. }
  68052. else {
  68053. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68054. }
  68055. if (SceneLoader.ShowLoadingScreen) {
  68056. scene.executeWhenReady(function () {
  68057. scene.getEngine().hideLoadingUI();
  68058. });
  68059. }
  68060. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68061. };
  68062. /**
  68063. * Load a scene into an asset container
  68064. * @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)
  68065. * @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)
  68066. * @param scene is the instance of BABYLON.Scene to append to
  68067. * @param onProgress a callback with a progress event for each file being loaded
  68068. * @param pluginExtension the extension used to determine the plugin
  68069. * @returns The loaded asset container
  68070. */
  68071. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68072. if (sceneFilename === void 0) { sceneFilename = ""; }
  68073. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68074. if (onProgress === void 0) { onProgress = null; }
  68075. if (pluginExtension === void 0) { pluginExtension = null; }
  68076. return new Promise(function (resolve, reject) {
  68077. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68078. resolve(assetContainer);
  68079. }, onProgress, function (scene, message, exception) {
  68080. reject(exception || new Error(message));
  68081. }, pluginExtension);
  68082. });
  68083. };
  68084. // Flags
  68085. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68086. SceneLoader._ShowLoadingScreen = true;
  68087. SceneLoader._CleanBoneMatrixWeights = false;
  68088. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68089. // Members
  68090. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68091. SceneLoader._registeredPlugins = {};
  68092. return SceneLoader;
  68093. }());
  68094. BABYLON.SceneLoader = SceneLoader;
  68095. ;
  68096. })(BABYLON || (BABYLON = {}));
  68097. //# sourceMappingURL=babylon.sceneLoader.js.map
  68098. var BABYLON;
  68099. (function (BABYLON) {
  68100. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68101. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68102. var parsedMaterial = parsedData.materials[index];
  68103. if (parsedMaterial.id === id) {
  68104. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68105. }
  68106. }
  68107. return null;
  68108. };
  68109. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68110. for (var i in names) {
  68111. if (mesh.name === names[i]) {
  68112. hierarchyIds.push(mesh.id);
  68113. return true;
  68114. }
  68115. }
  68116. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68117. hierarchyIds.push(mesh.id);
  68118. return true;
  68119. }
  68120. return false;
  68121. };
  68122. var logOperation = function (operation, producer) {
  68123. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68124. };
  68125. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68126. if (addToScene === void 0) { addToScene = false; }
  68127. var container = new BABYLON.AssetContainer(scene);
  68128. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68129. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68130. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68131. // and avoid problems with multiple concurrent .babylon loads.
  68132. var log = "importScene has failed JSON parse";
  68133. try {
  68134. var parsedData = JSON.parse(data);
  68135. log = "";
  68136. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68137. var index;
  68138. var cache;
  68139. // Lights
  68140. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68141. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68142. var parsedLight = parsedData.lights[index];
  68143. var light = BABYLON.Light.Parse(parsedLight, scene);
  68144. if (light) {
  68145. container.lights.push(light);
  68146. log += (index === 0 ? "\n\tLights:" : "");
  68147. log += "\n\t\t" + light.toString(fullDetails);
  68148. }
  68149. }
  68150. }
  68151. // Animations
  68152. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68153. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68154. var parsedAnimation = parsedData.animations[index];
  68155. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68156. scene.animations.push(animation);
  68157. container.animations.push(animation);
  68158. log += (index === 0 ? "\n\tAnimations:" : "");
  68159. log += "\n\t\t" + animation.toString(fullDetails);
  68160. }
  68161. }
  68162. // Materials
  68163. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68164. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68165. var parsedMaterial = parsedData.materials[index];
  68166. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68167. container.materials.push(mat);
  68168. log += (index === 0 ? "\n\tMaterials:" : "");
  68169. log += "\n\t\t" + mat.toString(fullDetails);
  68170. }
  68171. }
  68172. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68173. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68174. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68175. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68176. container.multiMaterials.push(mmat);
  68177. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68178. log += "\n\t\t" + mmat.toString(fullDetails);
  68179. }
  68180. }
  68181. // Morph targets
  68182. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68183. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68184. var managerData = _a[_i];
  68185. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68186. }
  68187. }
  68188. // Skeletons
  68189. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68190. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68191. var parsedSkeleton = parsedData.skeletons[index];
  68192. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68193. container.skeletons.push(skeleton);
  68194. log += (index === 0 ? "\n\tSkeletons:" : "");
  68195. log += "\n\t\t" + skeleton.toString(fullDetails);
  68196. }
  68197. }
  68198. // Geometries
  68199. var geometries = parsedData.geometries;
  68200. if (geometries !== undefined && geometries !== null) {
  68201. var addedGeometry = new Array();
  68202. // Boxes
  68203. var boxes = geometries.boxes;
  68204. if (boxes !== undefined && boxes !== null) {
  68205. for (index = 0, cache = boxes.length; index < cache; index++) {
  68206. var parsedBox = boxes[index];
  68207. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68208. }
  68209. }
  68210. // Spheres
  68211. var spheres = geometries.spheres;
  68212. if (spheres !== undefined && spheres !== null) {
  68213. for (index = 0, cache = spheres.length; index < cache; index++) {
  68214. var parsedSphere = spheres[index];
  68215. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68216. }
  68217. }
  68218. // Cylinders
  68219. var cylinders = geometries.cylinders;
  68220. if (cylinders !== undefined && cylinders !== null) {
  68221. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68222. var parsedCylinder = cylinders[index];
  68223. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68224. }
  68225. }
  68226. // Toruses
  68227. var toruses = geometries.toruses;
  68228. if (toruses !== undefined && toruses !== null) {
  68229. for (index = 0, cache = toruses.length; index < cache; index++) {
  68230. var parsedTorus = toruses[index];
  68231. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68232. }
  68233. }
  68234. // Grounds
  68235. var grounds = geometries.grounds;
  68236. if (grounds !== undefined && grounds !== null) {
  68237. for (index = 0, cache = grounds.length; index < cache; index++) {
  68238. var parsedGround = grounds[index];
  68239. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68240. }
  68241. }
  68242. // Planes
  68243. var planes = geometries.planes;
  68244. if (planes !== undefined && planes !== null) {
  68245. for (index = 0, cache = planes.length; index < cache; index++) {
  68246. var parsedPlane = planes[index];
  68247. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68248. }
  68249. }
  68250. // TorusKnots
  68251. var torusKnots = geometries.torusKnots;
  68252. if (torusKnots !== undefined && torusKnots !== null) {
  68253. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68254. var parsedTorusKnot = torusKnots[index];
  68255. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68256. }
  68257. }
  68258. // VertexData
  68259. var vertexData = geometries.vertexData;
  68260. if (vertexData !== undefined && vertexData !== null) {
  68261. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68262. var parsedVertexData = vertexData[index];
  68263. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68264. }
  68265. }
  68266. addedGeometry.forEach(function (g) {
  68267. if (g) {
  68268. container.geometries.push(g);
  68269. }
  68270. });
  68271. }
  68272. // Transform nodes
  68273. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68274. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68275. var parsedTransformNode = parsedData.transformNodes[index];
  68276. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68277. container.transformNodes.push(node);
  68278. }
  68279. }
  68280. // Meshes
  68281. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68282. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68283. var parsedMesh = parsedData.meshes[index];
  68284. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68285. container.meshes.push(mesh);
  68286. log += (index === 0 ? "\n\tMeshes:" : "");
  68287. log += "\n\t\t" + mesh.toString(fullDetails);
  68288. }
  68289. }
  68290. // Cameras
  68291. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68292. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68293. var parsedCamera = parsedData.cameras[index];
  68294. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68295. container.cameras.push(camera);
  68296. log += (index === 0 ? "\n\tCameras:" : "");
  68297. log += "\n\t\t" + camera.toString(fullDetails);
  68298. }
  68299. }
  68300. // Browsing all the graph to connect the dots
  68301. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68302. var camera = scene.cameras[index];
  68303. if (camera._waitingParentId) {
  68304. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68305. camera._waitingParentId = null;
  68306. }
  68307. }
  68308. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68309. var light_1 = scene.lights[index];
  68310. if (light_1 && light_1._waitingParentId) {
  68311. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68312. light_1._waitingParentId = null;
  68313. }
  68314. }
  68315. // Sounds
  68316. // TODO: add sound
  68317. var loadedSounds = [];
  68318. var loadedSound;
  68319. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68320. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68321. var parsedSound = parsedData.sounds[index];
  68322. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68323. if (!parsedSound.url)
  68324. parsedSound.url = parsedSound.name;
  68325. if (!loadedSounds[parsedSound.url]) {
  68326. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68327. loadedSounds[parsedSound.url] = loadedSound;
  68328. container.sounds.push(loadedSound);
  68329. }
  68330. else {
  68331. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68332. }
  68333. }
  68334. else {
  68335. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68336. }
  68337. }
  68338. }
  68339. loadedSounds = [];
  68340. // Connect parents & children and parse actions
  68341. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68342. var transformNode = scene.transformNodes[index];
  68343. if (transformNode._waitingParentId) {
  68344. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68345. transformNode._waitingParentId = null;
  68346. }
  68347. }
  68348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68349. var mesh = scene.meshes[index];
  68350. if (mesh._waitingParentId) {
  68351. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68352. mesh._waitingParentId = null;
  68353. }
  68354. if (mesh._waitingActions) {
  68355. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68356. mesh._waitingActions = null;
  68357. }
  68358. }
  68359. // freeze world matrix application
  68360. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68361. var currentMesh = scene.meshes[index];
  68362. if (currentMesh._waitingFreezeWorldMatrix) {
  68363. currentMesh.freezeWorldMatrix();
  68364. currentMesh._waitingFreezeWorldMatrix = null;
  68365. }
  68366. else {
  68367. currentMesh.computeWorldMatrix(true);
  68368. }
  68369. }
  68370. // Particles Systems
  68371. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68372. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68373. var parsedParticleSystem = parsedData.particleSystems[index];
  68374. if (parsedParticleSystem.activeParticleCount) {
  68375. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68376. container.particleSystems.push(ps);
  68377. }
  68378. else {
  68379. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68380. container.particleSystems.push(ps);
  68381. }
  68382. }
  68383. }
  68384. // Lens flares
  68385. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68386. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68387. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68388. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68389. container.lensFlareSystems.push(lf);
  68390. }
  68391. }
  68392. // Shadows
  68393. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68394. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68395. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68396. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68397. container.shadowGenerators.push(sg);
  68398. }
  68399. }
  68400. // Lights exclusions / inclusions
  68401. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68402. var light_2 = scene.lights[index];
  68403. // Excluded check
  68404. if (light_2._excludedMeshesIds.length > 0) {
  68405. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68406. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68407. if (excludedMesh) {
  68408. light_2.excludedMeshes.push(excludedMesh);
  68409. }
  68410. }
  68411. light_2._excludedMeshesIds = [];
  68412. }
  68413. // Included check
  68414. if (light_2._includedOnlyMeshesIds.length > 0) {
  68415. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68416. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68417. if (includedOnlyMesh) {
  68418. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68419. }
  68420. }
  68421. light_2._includedOnlyMeshesIds = [];
  68422. }
  68423. }
  68424. // Effect layers
  68425. if (parsedData.effectLayers) {
  68426. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68427. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68428. container.effectLayers.push(effectLayer);
  68429. }
  68430. }
  68431. // Actions (scene)
  68432. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68433. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68434. }
  68435. if (!addToScene) {
  68436. container.removeAllFromScene();
  68437. }
  68438. }
  68439. catch (err) {
  68440. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68441. if (onError) {
  68442. onError(msg, err);
  68443. }
  68444. else {
  68445. BABYLON.Tools.Log(msg);
  68446. throw err;
  68447. }
  68448. }
  68449. finally {
  68450. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68451. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68452. }
  68453. }
  68454. return container;
  68455. };
  68456. BABYLON.SceneLoader.RegisterPlugin({
  68457. name: "babylon.js",
  68458. extensions: ".babylon",
  68459. canDirectLoad: function (data) {
  68460. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68461. return true;
  68462. }
  68463. return false;
  68464. },
  68465. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68466. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68467. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68468. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68469. // and avoid problems with multiple concurrent .babylon loads.
  68470. var log = "importMesh has failed JSON parse";
  68471. try {
  68472. var parsedData = JSON.parse(data);
  68473. log = "";
  68474. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68475. if (!meshesNames) {
  68476. meshesNames = null;
  68477. }
  68478. else if (!Array.isArray(meshesNames)) {
  68479. meshesNames = [meshesNames];
  68480. }
  68481. var hierarchyIds = new Array();
  68482. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68483. var loadedSkeletonsIds = [];
  68484. var loadedMaterialsIds = [];
  68485. var index;
  68486. var cache;
  68487. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68488. var parsedMesh = parsedData.meshes[index];
  68489. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68490. if (meshesNames !== null) {
  68491. // Remove found mesh name from list.
  68492. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68493. }
  68494. //Geometry?
  68495. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68496. //does the file contain geometries?
  68497. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68498. //find the correct geometry and add it to the scene
  68499. var found = false;
  68500. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68501. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68502. return;
  68503. }
  68504. else {
  68505. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68506. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68507. switch (geometryType) {
  68508. case "boxes":
  68509. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68510. break;
  68511. case "spheres":
  68512. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68513. break;
  68514. case "cylinders":
  68515. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68516. break;
  68517. case "toruses":
  68518. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68519. break;
  68520. case "grounds":
  68521. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68522. break;
  68523. case "planes":
  68524. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68525. break;
  68526. case "torusKnots":
  68527. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68528. break;
  68529. case "vertexData":
  68530. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68531. break;
  68532. }
  68533. found = true;
  68534. }
  68535. });
  68536. }
  68537. });
  68538. if (found === false) {
  68539. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68540. }
  68541. }
  68542. }
  68543. // Material ?
  68544. if (parsedMesh.materialId) {
  68545. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68546. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68547. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68548. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68549. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68550. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68551. var subMatId = parsedMultiMaterial.materials[matIndex];
  68552. loadedMaterialsIds.push(subMatId);
  68553. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68554. if (mat) {
  68555. log += "\n\tMaterial " + mat.toString(fullDetails);
  68556. }
  68557. }
  68558. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68559. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68560. if (mmat) {
  68561. materialFound = true;
  68562. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68563. }
  68564. break;
  68565. }
  68566. }
  68567. }
  68568. if (materialFound === false) {
  68569. loadedMaterialsIds.push(parsedMesh.materialId);
  68570. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68571. if (!mat) {
  68572. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68573. }
  68574. else {
  68575. log += "\n\tMaterial " + mat.toString(fullDetails);
  68576. }
  68577. }
  68578. }
  68579. // Skeleton ?
  68580. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68581. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68582. if (skeletonAlreadyLoaded === false) {
  68583. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68584. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68585. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68586. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68587. skeletons.push(skeleton);
  68588. loadedSkeletonsIds.push(parsedSkeleton.id);
  68589. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68590. }
  68591. }
  68592. }
  68593. }
  68594. // Morph targets ?
  68595. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68596. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68597. var managerData = _a[_i];
  68598. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68599. }
  68600. }
  68601. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68602. meshes.push(mesh);
  68603. log += "\n\tMesh " + mesh.toString(fullDetails);
  68604. }
  68605. }
  68606. // Connecting parents
  68607. var currentMesh;
  68608. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68609. currentMesh = scene.meshes[index];
  68610. if (currentMesh._waitingParentId) {
  68611. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68612. currentMesh._waitingParentId = null;
  68613. }
  68614. }
  68615. // freeze and compute world matrix application
  68616. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68617. currentMesh = scene.meshes[index];
  68618. if (currentMesh._waitingFreezeWorldMatrix) {
  68619. currentMesh.freezeWorldMatrix();
  68620. currentMesh._waitingFreezeWorldMatrix = null;
  68621. }
  68622. else {
  68623. currentMesh.computeWorldMatrix(true);
  68624. }
  68625. }
  68626. }
  68627. // Particles
  68628. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68629. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68630. var parsedParticleSystem = parsedData.particleSystems[index];
  68631. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68632. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68633. }
  68634. }
  68635. }
  68636. return true;
  68637. }
  68638. catch (err) {
  68639. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68640. if (onError) {
  68641. onError(msg, err);
  68642. }
  68643. else {
  68644. BABYLON.Tools.Log(msg);
  68645. throw err;
  68646. }
  68647. }
  68648. finally {
  68649. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68650. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68651. }
  68652. }
  68653. return false;
  68654. },
  68655. load: function (scene, data, rootUrl, onError) {
  68656. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68657. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68658. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68659. // and avoid problems with multiple concurrent .babylon loads.
  68660. var log = "importScene has failed JSON parse";
  68661. try {
  68662. var parsedData = JSON.parse(data);
  68663. log = "";
  68664. // Scene
  68665. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68666. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68667. }
  68668. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68669. scene.autoClear = parsedData.autoClear;
  68670. }
  68671. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68672. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68673. }
  68674. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68675. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68676. }
  68677. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68678. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68679. }
  68680. // Fog
  68681. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68682. scene.fogMode = parsedData.fogMode;
  68683. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68684. scene.fogStart = parsedData.fogStart;
  68685. scene.fogEnd = parsedData.fogEnd;
  68686. scene.fogDensity = parsedData.fogDensity;
  68687. log += "\tFog mode for scene: ";
  68688. switch (scene.fogMode) {
  68689. // getters not compiling, so using hardcoded
  68690. case 1:
  68691. log += "exp\n";
  68692. break;
  68693. case 2:
  68694. log += "exp2\n";
  68695. break;
  68696. case 3:
  68697. log += "linear\n";
  68698. break;
  68699. }
  68700. }
  68701. //Physics
  68702. if (parsedData.physicsEnabled) {
  68703. var physicsPlugin;
  68704. if (parsedData.physicsEngine === "cannon") {
  68705. physicsPlugin = new BABYLON.CannonJSPlugin();
  68706. }
  68707. else if (parsedData.physicsEngine === "oimo") {
  68708. physicsPlugin = new BABYLON.OimoJSPlugin();
  68709. }
  68710. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68711. //else - default engine, which is currently oimo
  68712. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68713. scene.enablePhysics(physicsGravity, physicsPlugin);
  68714. }
  68715. // Metadata
  68716. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68717. scene.metadata = parsedData.metadata;
  68718. }
  68719. //collisions, if defined. otherwise, default is true
  68720. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68721. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68722. }
  68723. scene.workerCollisions = !!parsedData.workerCollisions;
  68724. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68725. if (!container) {
  68726. return false;
  68727. }
  68728. if (parsedData.autoAnimate) {
  68729. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68730. }
  68731. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68732. scene.setActiveCameraByID(parsedData.activeCameraID);
  68733. }
  68734. // Environment texture
  68735. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68736. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68737. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68738. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68739. if (parsedData.environmentTextureRotationY) {
  68740. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68741. }
  68742. scene.environmentTexture = hdrTexture;
  68743. }
  68744. else {
  68745. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68746. if (parsedData.environmentTextureRotationY) {
  68747. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68748. }
  68749. scene.environmentTexture = cubeTexture;
  68750. }
  68751. if (parsedData.createDefaultSkybox === true) {
  68752. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68753. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68754. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68755. }
  68756. }
  68757. // Finish
  68758. return true;
  68759. }
  68760. catch (err) {
  68761. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68762. if (onError) {
  68763. onError(msg, err);
  68764. }
  68765. else {
  68766. BABYLON.Tools.Log(msg);
  68767. throw err;
  68768. }
  68769. }
  68770. finally {
  68771. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68772. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68773. }
  68774. }
  68775. return false;
  68776. },
  68777. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68778. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68779. return container;
  68780. }
  68781. });
  68782. })(BABYLON || (BABYLON = {}));
  68783. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68784. var BABYLON;
  68785. (function (BABYLON) {
  68786. var FilesInput = /** @class */ (function () {
  68787. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68788. this.onProcessFileCallback = function () { return true; };
  68789. this._engine = engine;
  68790. this._currentScene = scene;
  68791. this._sceneLoadedCallback = sceneLoadedCallback;
  68792. this._progressCallback = progressCallback;
  68793. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68794. this._textureLoadingCallback = textureLoadingCallback;
  68795. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68796. this._onReloadCallback = onReloadCallback;
  68797. this._errorCallback = errorCallback;
  68798. }
  68799. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68800. var _this = this;
  68801. if (elementToMonitor) {
  68802. this._elementToMonitor = elementToMonitor;
  68803. this._dragEnterHandler = function (e) { _this.drag(e); };
  68804. this._dragOverHandler = function (e) { _this.drag(e); };
  68805. this._dropHandler = function (e) { _this.drop(e); };
  68806. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68807. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68808. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68809. }
  68810. };
  68811. FilesInput.prototype.dispose = function () {
  68812. if (!this._elementToMonitor) {
  68813. return;
  68814. }
  68815. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68816. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68817. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68818. };
  68819. FilesInput.prototype.renderFunction = function () {
  68820. if (this._additionalRenderLoopLogicCallback) {
  68821. this._additionalRenderLoopLogicCallback();
  68822. }
  68823. if (this._currentScene) {
  68824. if (this._textureLoadingCallback) {
  68825. var remaining = this._currentScene.getWaitingItemsCount();
  68826. if (remaining > 0) {
  68827. this._textureLoadingCallback(remaining);
  68828. }
  68829. }
  68830. this._currentScene.render();
  68831. }
  68832. };
  68833. FilesInput.prototype.drag = function (e) {
  68834. e.stopPropagation();
  68835. e.preventDefault();
  68836. };
  68837. FilesInput.prototype.drop = function (eventDrop) {
  68838. eventDrop.stopPropagation();
  68839. eventDrop.preventDefault();
  68840. this.loadFiles(eventDrop);
  68841. };
  68842. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68843. var _this = this;
  68844. var reader = folder.createReader();
  68845. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68846. reader.readEntries(function (entries) {
  68847. remaining.count += entries.length;
  68848. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68849. var entry = entries_1[_i];
  68850. if (entry.isFile) {
  68851. entry.file(function (file) {
  68852. file.correctName = relativePath + file.name;
  68853. files.push(file);
  68854. if (--remaining.count === 0) {
  68855. callback();
  68856. }
  68857. });
  68858. }
  68859. else if (entry.isDirectory) {
  68860. _this._traverseFolder(entry, files, remaining, callback);
  68861. }
  68862. }
  68863. if (--remaining.count) {
  68864. callback();
  68865. }
  68866. });
  68867. };
  68868. FilesInput.prototype._processFiles = function (files) {
  68869. for (var i = 0; i < files.length; i++) {
  68870. var name = files[i].correctName.toLowerCase();
  68871. var extension = name.split('.').pop();
  68872. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68873. continue;
  68874. }
  68875. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68876. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68877. this._sceneFileToLoad = files[i];
  68878. }
  68879. else {
  68880. FilesInput.FilesToLoad[name] = files[i];
  68881. }
  68882. }
  68883. };
  68884. FilesInput.prototype.loadFiles = function (event) {
  68885. var _this = this;
  68886. if (this._startingProcessingFilesCallback)
  68887. this._startingProcessingFilesCallback();
  68888. // Handling data transfer via drag'n'drop
  68889. if (event && event.dataTransfer && event.dataTransfer.files) {
  68890. this._filesToLoad = event.dataTransfer.files;
  68891. }
  68892. // Handling files from input files
  68893. if (event && event.target && event.target.files) {
  68894. this._filesToLoad = event.target.files;
  68895. }
  68896. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68897. var files_1 = new Array();
  68898. var folders = [];
  68899. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68900. for (var i = 0; i < this._filesToLoad.length; i++) {
  68901. var fileToLoad = this._filesToLoad[i];
  68902. var name_1 = fileToLoad.name.toLowerCase();
  68903. var entry = void 0;
  68904. fileToLoad.correctName = name_1;
  68905. if (items) {
  68906. var item = items[i];
  68907. if (item.getAsEntry) {
  68908. entry = item.getAsEntry();
  68909. }
  68910. else if (item.webkitGetAsEntry) {
  68911. entry = item.webkitGetAsEntry();
  68912. }
  68913. }
  68914. if (!entry) {
  68915. files_1.push(fileToLoad);
  68916. }
  68917. else {
  68918. if (entry.isDirectory) {
  68919. folders.push(entry);
  68920. }
  68921. else {
  68922. files_1.push(fileToLoad);
  68923. }
  68924. }
  68925. }
  68926. if (folders.length === 0) {
  68927. this._processFiles(files_1);
  68928. this._processReload();
  68929. }
  68930. else {
  68931. var remaining = { count: folders.length };
  68932. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68933. var folder = folders_1[_i];
  68934. this._traverseFolder(folder, files_1, remaining, function () {
  68935. _this._processFiles(files_1);
  68936. if (remaining.count === 0) {
  68937. _this._processReload();
  68938. }
  68939. });
  68940. }
  68941. }
  68942. }
  68943. };
  68944. FilesInput.prototype._processReload = function () {
  68945. if (this._onReloadCallback) {
  68946. this._onReloadCallback(this._sceneFileToLoad);
  68947. }
  68948. else {
  68949. this.reload();
  68950. }
  68951. };
  68952. FilesInput.prototype.reload = function () {
  68953. var _this = this;
  68954. // If a scene file has been provided
  68955. if (this._sceneFileToLoad) {
  68956. if (this._currentScene) {
  68957. if (BABYLON.Tools.errorsCount > 0) {
  68958. BABYLON.Tools.ClearLogCache();
  68959. }
  68960. this._engine.stopRenderLoop();
  68961. }
  68962. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68963. if (_this._progressCallback) {
  68964. _this._progressCallback(progress);
  68965. }
  68966. }).then(function (scene) {
  68967. if (_this._currentScene) {
  68968. _this._currentScene.dispose();
  68969. }
  68970. _this._currentScene = scene;
  68971. if (_this._sceneLoadedCallback) {
  68972. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68973. }
  68974. // Wait for textures and shaders to be ready
  68975. _this._currentScene.executeWhenReady(function () {
  68976. _this._engine.runRenderLoop(function () {
  68977. _this.renderFunction();
  68978. });
  68979. });
  68980. }).catch(function (error) {
  68981. if (_this._errorCallback) {
  68982. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68983. }
  68984. });
  68985. }
  68986. else {
  68987. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68988. }
  68989. };
  68990. FilesInput.FilesToLoad = {};
  68991. return FilesInput;
  68992. }());
  68993. BABYLON.FilesInput = FilesInput;
  68994. })(BABYLON || (BABYLON = {}));
  68995. //# sourceMappingURL=babylon.filesInput.js.map
  68996. var BABYLON;
  68997. (function (BABYLON) {
  68998. /**
  68999. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69000. * The underlying implementation relies on an associative array to ensure the best performances.
  69001. * The value can be anything including 'null' but except 'undefined'
  69002. */
  69003. var StringDictionary = /** @class */ (function () {
  69004. function StringDictionary() {
  69005. this._count = 0;
  69006. this._data = {};
  69007. }
  69008. /**
  69009. * This will clear this dictionary and copy the content from the 'source' one.
  69010. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69011. * @param source the dictionary to take the content from and copy to this dictionary
  69012. */
  69013. StringDictionary.prototype.copyFrom = function (source) {
  69014. var _this = this;
  69015. this.clear();
  69016. source.forEach(function (t, v) { return _this.add(t, v); });
  69017. };
  69018. /**
  69019. * Get a value based from its key
  69020. * @param key the given key to get the matching value from
  69021. * @return the value if found, otherwise undefined is returned
  69022. */
  69023. StringDictionary.prototype.get = function (key) {
  69024. var val = this._data[key];
  69025. if (val !== undefined) {
  69026. return val;
  69027. }
  69028. return undefined;
  69029. };
  69030. /**
  69031. * Get a value from its key or add it if it doesn't exist.
  69032. * This method will ensure you that a given key/data will be present in the dictionary.
  69033. * @param key the given key to get the matching value from
  69034. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69035. * The factory will only be invoked if there's no data for the given key.
  69036. * @return the value corresponding to the key.
  69037. */
  69038. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69039. var val = this.get(key);
  69040. if (val !== undefined) {
  69041. return val;
  69042. }
  69043. val = factory(key);
  69044. if (val) {
  69045. this.add(key, val);
  69046. }
  69047. return val;
  69048. };
  69049. /**
  69050. * Get a value from its key if present in the dictionary otherwise add it
  69051. * @param key the key to get the value from
  69052. * @param val if there's no such key/value pair in the dictionary add it with this value
  69053. * @return the value corresponding to the key
  69054. */
  69055. StringDictionary.prototype.getOrAdd = function (key, val) {
  69056. var curVal = this.get(key);
  69057. if (curVal !== undefined) {
  69058. return curVal;
  69059. }
  69060. this.add(key, val);
  69061. return val;
  69062. };
  69063. /**
  69064. * Check if there's a given key in the dictionary
  69065. * @param key the key to check for
  69066. * @return true if the key is present, false otherwise
  69067. */
  69068. StringDictionary.prototype.contains = function (key) {
  69069. return this._data[key] !== undefined;
  69070. };
  69071. /**
  69072. * Add a new key and its corresponding value
  69073. * @param key the key to add
  69074. * @param value the value corresponding to the key
  69075. * @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
  69076. */
  69077. StringDictionary.prototype.add = function (key, value) {
  69078. if (this._data[key] !== undefined) {
  69079. return false;
  69080. }
  69081. this._data[key] = value;
  69082. ++this._count;
  69083. return true;
  69084. };
  69085. StringDictionary.prototype.set = function (key, value) {
  69086. if (this._data[key] === undefined) {
  69087. return false;
  69088. }
  69089. this._data[key] = value;
  69090. return true;
  69091. };
  69092. /**
  69093. * Get the element of the given key and remove it from the dictionary
  69094. * @param key
  69095. */
  69096. StringDictionary.prototype.getAndRemove = function (key) {
  69097. var val = this.get(key);
  69098. if (val !== undefined) {
  69099. delete this._data[key];
  69100. --this._count;
  69101. return val;
  69102. }
  69103. return null;
  69104. };
  69105. /**
  69106. * Remove a key/value from the dictionary.
  69107. * @param key the key to remove
  69108. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69109. */
  69110. StringDictionary.prototype.remove = function (key) {
  69111. if (this.contains(key)) {
  69112. delete this._data[key];
  69113. --this._count;
  69114. return true;
  69115. }
  69116. return false;
  69117. };
  69118. /**
  69119. * Clear the whole content of the dictionary
  69120. */
  69121. StringDictionary.prototype.clear = function () {
  69122. this._data = {};
  69123. this._count = 0;
  69124. };
  69125. Object.defineProperty(StringDictionary.prototype, "count", {
  69126. get: function () {
  69127. return this._count;
  69128. },
  69129. enumerable: true,
  69130. configurable: true
  69131. });
  69132. /**
  69133. * Execute a callback on each key/val of the dictionary.
  69134. * Note that you can remove any element in this dictionary in the callback implementation
  69135. * @param callback the callback to execute on a given key/value pair
  69136. */
  69137. StringDictionary.prototype.forEach = function (callback) {
  69138. for (var cur in this._data) {
  69139. var val = this._data[cur];
  69140. callback(cur, val);
  69141. }
  69142. };
  69143. /**
  69144. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69145. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69146. * Note that you can remove any element in this dictionary in the callback implementation
  69147. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69148. */
  69149. StringDictionary.prototype.first = function (callback) {
  69150. for (var cur in this._data) {
  69151. var val = this._data[cur];
  69152. var res = callback(cur, val);
  69153. if (res) {
  69154. return res;
  69155. }
  69156. }
  69157. return null;
  69158. };
  69159. return StringDictionary;
  69160. }());
  69161. BABYLON.StringDictionary = StringDictionary;
  69162. })(BABYLON || (BABYLON = {}));
  69163. //# sourceMappingURL=babylon.stringDictionary.js.map
  69164. var BABYLON;
  69165. (function (BABYLON) {
  69166. var Tags = /** @class */ (function () {
  69167. function Tags() {
  69168. }
  69169. Tags.EnableFor = function (obj) {
  69170. obj._tags = obj._tags || {};
  69171. obj.hasTags = function () {
  69172. return Tags.HasTags(obj);
  69173. };
  69174. obj.addTags = function (tagsString) {
  69175. return Tags.AddTagsTo(obj, tagsString);
  69176. };
  69177. obj.removeTags = function (tagsString) {
  69178. return Tags.RemoveTagsFrom(obj, tagsString);
  69179. };
  69180. obj.matchesTagsQuery = function (tagsQuery) {
  69181. return Tags.MatchesQuery(obj, tagsQuery);
  69182. };
  69183. };
  69184. Tags.DisableFor = function (obj) {
  69185. delete obj._tags;
  69186. delete obj.hasTags;
  69187. delete obj.addTags;
  69188. delete obj.removeTags;
  69189. delete obj.matchesTagsQuery;
  69190. };
  69191. Tags.HasTags = function (obj) {
  69192. if (!obj._tags) {
  69193. return false;
  69194. }
  69195. return !BABYLON.Tools.IsEmpty(obj._tags);
  69196. };
  69197. Tags.GetTags = function (obj, asString) {
  69198. if (asString === void 0) { asString = true; }
  69199. if (!obj._tags) {
  69200. return null;
  69201. }
  69202. if (asString) {
  69203. var tagsArray = [];
  69204. for (var tag in obj._tags) {
  69205. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69206. tagsArray.push(tag);
  69207. }
  69208. }
  69209. return tagsArray.join(" ");
  69210. }
  69211. else {
  69212. return obj._tags;
  69213. }
  69214. };
  69215. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69216. // a tag cannot start with '||', '&&', and '!'
  69217. // it cannot contain whitespaces
  69218. Tags.AddTagsTo = function (obj, tagsString) {
  69219. if (!tagsString) {
  69220. return;
  69221. }
  69222. if (typeof tagsString !== "string") {
  69223. return;
  69224. }
  69225. var tags = tagsString.split(" ");
  69226. tags.forEach(function (tag, index, array) {
  69227. Tags._AddTagTo(obj, tag);
  69228. });
  69229. };
  69230. Tags._AddTagTo = function (obj, tag) {
  69231. tag = tag.trim();
  69232. if (tag === "" || tag === "true" || tag === "false") {
  69233. return;
  69234. }
  69235. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69236. return;
  69237. }
  69238. Tags.EnableFor(obj);
  69239. obj._tags[tag] = true;
  69240. };
  69241. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69242. if (!Tags.HasTags(obj)) {
  69243. return;
  69244. }
  69245. var tags = tagsString.split(" ");
  69246. for (var t in tags) {
  69247. Tags._RemoveTagFrom(obj, tags[t]);
  69248. }
  69249. };
  69250. Tags._RemoveTagFrom = function (obj, tag) {
  69251. delete obj._tags[tag];
  69252. };
  69253. Tags.MatchesQuery = function (obj, tagsQuery) {
  69254. if (tagsQuery === undefined) {
  69255. return true;
  69256. }
  69257. if (tagsQuery === "") {
  69258. return Tags.HasTags(obj);
  69259. }
  69260. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69261. };
  69262. return Tags;
  69263. }());
  69264. BABYLON.Tags = Tags;
  69265. })(BABYLON || (BABYLON = {}));
  69266. //# sourceMappingURL=babylon.tags.js.map
  69267. var BABYLON;
  69268. (function (BABYLON) {
  69269. /**
  69270. * Class used to evalaute queries containing `and` and `or` operators
  69271. */
  69272. var AndOrNotEvaluator = /** @class */ (function () {
  69273. function AndOrNotEvaluator() {
  69274. }
  69275. /**
  69276. * Evaluate a query
  69277. * @param query defines the query to evaluate
  69278. * @param evaluateCallback defines the callback used to filter result
  69279. * @returns true if the query matches
  69280. */
  69281. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69282. if (!query.match(/\([^\(\)]*\)/g)) {
  69283. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69284. }
  69285. else {
  69286. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69287. // remove parenthesis
  69288. r = r.slice(1, r.length - 1);
  69289. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69290. });
  69291. }
  69292. if (query === "true") {
  69293. return true;
  69294. }
  69295. if (query === "false") {
  69296. return false;
  69297. }
  69298. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69299. };
  69300. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69301. evaluateCallback = evaluateCallback || (function (r) {
  69302. return r === "true" ? true : false;
  69303. });
  69304. var result;
  69305. var or = parenthesisContent.split("||");
  69306. for (var i in or) {
  69307. if (or.hasOwnProperty(i)) {
  69308. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69309. var and = ori.split("&&");
  69310. if (and.length > 1) {
  69311. for (var j = 0; j < and.length; ++j) {
  69312. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69313. if (andj !== "true" && andj !== "false") {
  69314. if (andj[0] === "!") {
  69315. result = !evaluateCallback(andj.substring(1));
  69316. }
  69317. else {
  69318. result = evaluateCallback(andj);
  69319. }
  69320. }
  69321. else {
  69322. result = andj === "true" ? true : false;
  69323. }
  69324. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69325. ori = "false";
  69326. break;
  69327. }
  69328. }
  69329. }
  69330. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69331. result = true;
  69332. break;
  69333. }
  69334. // result equals false (or undefined)
  69335. if (ori !== "true" && ori !== "false") {
  69336. if (ori[0] === "!") {
  69337. result = !evaluateCallback(ori.substring(1));
  69338. }
  69339. else {
  69340. result = evaluateCallback(ori);
  69341. }
  69342. }
  69343. else {
  69344. result = ori === "true" ? true : false;
  69345. }
  69346. }
  69347. }
  69348. // the whole parenthesis scope is replaced by 'true' or 'false'
  69349. return result ? "true" : "false";
  69350. };
  69351. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69352. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69353. // remove whitespaces
  69354. r = r.replace(/[\s]/g, function () { return ""; });
  69355. return r.length % 2 ? "!" : "";
  69356. });
  69357. booleanString = booleanString.trim();
  69358. if (booleanString === "!true") {
  69359. booleanString = "false";
  69360. }
  69361. else if (booleanString === "!false") {
  69362. booleanString = "true";
  69363. }
  69364. return booleanString;
  69365. };
  69366. return AndOrNotEvaluator;
  69367. }());
  69368. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69369. })(BABYLON || (BABYLON = {}));
  69370. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69371. var BABYLON;
  69372. (function (BABYLON) {
  69373. /**
  69374. * Class used to enable access to IndexedDB
  69375. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69376. */
  69377. var Database = /** @class */ (function () {
  69378. /**
  69379. * Creates a new Database
  69380. * @param urlToScene defines the url to load the scene
  69381. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69382. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69383. */
  69384. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69385. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69386. var _this = this;
  69387. // Handling various flavors of prefixed version of IndexedDB
  69388. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69389. this.callbackManifestChecked = callbackManifestChecked;
  69390. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69391. this.db = null;
  69392. this._enableSceneOffline = false;
  69393. this._enableTexturesOffline = false;
  69394. this.manifestVersionFound = 0;
  69395. this.mustUpdateRessources = false;
  69396. this.hasReachedQuota = false;
  69397. if (!Database.IDBStorageEnabled) {
  69398. this.callbackManifestChecked(true);
  69399. }
  69400. else {
  69401. if (disableManifestCheck) {
  69402. this._enableSceneOffline = true;
  69403. this._enableTexturesOffline = true;
  69404. this.manifestVersionFound = 1;
  69405. BABYLON.Tools.SetImmediate(function () {
  69406. _this.callbackManifestChecked(true);
  69407. });
  69408. }
  69409. else {
  69410. this._checkManifestFile();
  69411. }
  69412. }
  69413. }
  69414. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69415. /**
  69416. * Gets a boolean indicating if scene must be saved in the database
  69417. */
  69418. get: function () {
  69419. return this._enableSceneOffline;
  69420. },
  69421. enumerable: true,
  69422. configurable: true
  69423. });
  69424. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69425. /**
  69426. * Gets a boolean indicating if textures must be saved in the database
  69427. */
  69428. get: function () {
  69429. return this._enableTexturesOffline;
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. Database.prototype._checkManifestFile = function () {
  69435. var _this = this;
  69436. var noManifestFile = function () {
  69437. _this._enableSceneOffline = false;
  69438. _this._enableTexturesOffline = false;
  69439. _this.callbackManifestChecked(false);
  69440. };
  69441. var timeStampUsed = false;
  69442. var manifestURL = this.currentSceneUrl + ".manifest";
  69443. var xhr = new XMLHttpRequest();
  69444. if (navigator.onLine) {
  69445. // Adding a timestamp to by-pass browsers' cache
  69446. timeStampUsed = true;
  69447. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69448. }
  69449. xhr.open("GET", manifestURL, true);
  69450. xhr.addEventListener("load", function () {
  69451. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69452. try {
  69453. var manifestFile = JSON.parse(xhr.response);
  69454. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69455. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69456. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69457. _this.manifestVersionFound = manifestFile.version;
  69458. }
  69459. if (_this.callbackManifestChecked) {
  69460. _this.callbackManifestChecked(true);
  69461. }
  69462. }
  69463. catch (ex) {
  69464. noManifestFile();
  69465. }
  69466. }
  69467. else {
  69468. noManifestFile();
  69469. }
  69470. }, false);
  69471. xhr.addEventListener("error", function (event) {
  69472. if (timeStampUsed) {
  69473. timeStampUsed = false;
  69474. // Let's retry without the timeStamp
  69475. // It could fail when coupled with HTML5 Offline API
  69476. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69477. xhr.open("GET", retryManifestURL, true);
  69478. xhr.send();
  69479. }
  69480. else {
  69481. noManifestFile();
  69482. }
  69483. }, false);
  69484. try {
  69485. xhr.send();
  69486. }
  69487. catch (ex) {
  69488. BABYLON.Tools.Error("Error on XHR send request.");
  69489. this.callbackManifestChecked(false);
  69490. }
  69491. };
  69492. /**
  69493. * Open the database and make it available
  69494. * @param successCallback defines the callback to call on success
  69495. * @param errorCallback defines the callback to call on error
  69496. */
  69497. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69498. var _this = this;
  69499. var handleError = function () {
  69500. _this.isSupported = false;
  69501. if (errorCallback)
  69502. errorCallback();
  69503. };
  69504. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69505. // Your browser doesn't support IndexedDB
  69506. this.isSupported = false;
  69507. if (errorCallback)
  69508. errorCallback();
  69509. }
  69510. else {
  69511. // If the DB hasn't been opened or created yet
  69512. if (!this.db) {
  69513. this.hasReachedQuota = false;
  69514. this.isSupported = true;
  69515. var request = this.idbFactory.open("babylonjs", 1);
  69516. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69517. request.onerror = function (event) {
  69518. handleError();
  69519. };
  69520. // executes when a version change transaction cannot complete due to other active transactions
  69521. request.onblocked = function (event) {
  69522. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69523. handleError();
  69524. };
  69525. // DB has been opened successfully
  69526. request.onsuccess = function (event) {
  69527. _this.db = request.result;
  69528. successCallback();
  69529. };
  69530. // Initialization of the DB. Creating Scenes & Textures stores
  69531. request.onupgradeneeded = function (event) {
  69532. _this.db = (event.target).result;
  69533. if (_this.db) {
  69534. try {
  69535. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69536. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69537. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69538. }
  69539. catch (ex) {
  69540. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69541. handleError();
  69542. }
  69543. }
  69544. };
  69545. }
  69546. // DB has already been created and opened
  69547. else {
  69548. if (successCallback)
  69549. successCallback();
  69550. }
  69551. }
  69552. };
  69553. /**
  69554. * Loads an image from the database
  69555. * @param url defines the url to load from
  69556. * @param image defines the target DOM image
  69557. */
  69558. Database.prototype.loadImageFromDB = function (url, image) {
  69559. var _this = this;
  69560. var completeURL = Database._ReturnFullUrlLocation(url);
  69561. var saveAndLoadImage = function () {
  69562. if (!_this.hasReachedQuota && _this.db !== null) {
  69563. // the texture is not yet in the DB, let's try to save it
  69564. _this._saveImageIntoDBAsync(completeURL, image);
  69565. }
  69566. // If the texture is not in the DB and we've reached the DB quota limit
  69567. // let's load it directly from the web
  69568. else {
  69569. image.src = url;
  69570. }
  69571. };
  69572. if (!this.mustUpdateRessources) {
  69573. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69574. }
  69575. // First time we're download the images or update requested in the manifest file by a version change
  69576. else {
  69577. saveAndLoadImage();
  69578. }
  69579. };
  69580. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69581. if (this.isSupported && this.db !== null) {
  69582. var texture;
  69583. var transaction = this.db.transaction(["textures"]);
  69584. transaction.onabort = function (event) {
  69585. image.src = url;
  69586. };
  69587. transaction.oncomplete = function (event) {
  69588. var blobTextureURL;
  69589. if (texture) {
  69590. var URL = window.URL || window.webkitURL;
  69591. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69592. image.onerror = function () {
  69593. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69594. image.src = url;
  69595. };
  69596. image.src = blobTextureURL;
  69597. }
  69598. else {
  69599. notInDBCallback();
  69600. }
  69601. };
  69602. var getRequest = transaction.objectStore("textures").get(url);
  69603. getRequest.onsuccess = function (event) {
  69604. texture = (event.target).result;
  69605. };
  69606. getRequest.onerror = function (event) {
  69607. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69608. image.src = url;
  69609. };
  69610. }
  69611. else {
  69612. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69613. image.src = url;
  69614. }
  69615. };
  69616. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69617. var _this = this;
  69618. if (this.isSupported) {
  69619. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69620. var generateBlobUrl = function () {
  69621. var blobTextureURL;
  69622. if (blob) {
  69623. var URL = window.URL || window.webkitURL;
  69624. try {
  69625. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69626. }
  69627. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69628. catch (ex) {
  69629. blobTextureURL = URL.createObjectURL(blob);
  69630. }
  69631. }
  69632. if (blobTextureURL) {
  69633. image.src = blobTextureURL;
  69634. }
  69635. };
  69636. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69637. var xhr = new XMLHttpRequest(), blob;
  69638. xhr.open("GET", url, true);
  69639. xhr.responseType = "blob";
  69640. xhr.addEventListener("load", function () {
  69641. if (xhr.status === 200 && _this.db) {
  69642. // Blob as response (XHR2)
  69643. blob = xhr.response;
  69644. var transaction = _this.db.transaction(["textures"], "readwrite");
  69645. // the transaction could abort because of a QuotaExceededError error
  69646. transaction.onabort = function (event) {
  69647. try {
  69648. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69649. var srcElement = (event.srcElement || event.target);
  69650. var error = srcElement.error;
  69651. if (error && error.name === "QuotaExceededError") {
  69652. _this.hasReachedQuota = true;
  69653. }
  69654. }
  69655. catch (ex) { }
  69656. generateBlobUrl();
  69657. };
  69658. transaction.oncomplete = function (event) {
  69659. generateBlobUrl();
  69660. };
  69661. var newTexture = { textureUrl: url, data: blob };
  69662. try {
  69663. // Put the blob into the dabase
  69664. var addRequest = transaction.objectStore("textures").put(newTexture);
  69665. addRequest.onsuccess = function (event) {
  69666. };
  69667. addRequest.onerror = function (event) {
  69668. generateBlobUrl();
  69669. };
  69670. }
  69671. catch (ex) {
  69672. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69673. if (ex.code === 25) {
  69674. Database.IsUASupportingBlobStorage = false;
  69675. }
  69676. image.src = url;
  69677. }
  69678. }
  69679. else {
  69680. image.src = url;
  69681. }
  69682. }, false);
  69683. xhr.addEventListener("error", function (event) {
  69684. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69685. image.src = url;
  69686. }, false);
  69687. xhr.send();
  69688. }
  69689. else {
  69690. image.src = url;
  69691. }
  69692. }
  69693. else {
  69694. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69695. image.src = url;
  69696. }
  69697. };
  69698. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69699. var _this = this;
  69700. var updateVersion = function () {
  69701. // the version is not yet in the DB or we need to update it
  69702. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69703. };
  69704. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69705. };
  69706. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69707. var _this = this;
  69708. if (this.isSupported && this.db) {
  69709. var version;
  69710. try {
  69711. var transaction = this.db.transaction(["versions"]);
  69712. transaction.oncomplete = function (event) {
  69713. if (version) {
  69714. // If the version in the JSON file is different from the version in DB
  69715. if (_this.manifestVersionFound !== version.data) {
  69716. _this.mustUpdateRessources = true;
  69717. updateInDBCallback();
  69718. }
  69719. else {
  69720. callback(version.data);
  69721. }
  69722. }
  69723. // version was not found in DB
  69724. else {
  69725. _this.mustUpdateRessources = true;
  69726. updateInDBCallback();
  69727. }
  69728. };
  69729. transaction.onabort = function (event) {
  69730. callback(-1);
  69731. };
  69732. var getRequest = transaction.objectStore("versions").get(url);
  69733. getRequest.onsuccess = function (event) {
  69734. version = (event.target).result;
  69735. };
  69736. getRequest.onerror = function (event) {
  69737. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69738. callback(-1);
  69739. };
  69740. }
  69741. catch (ex) {
  69742. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69743. callback(-1);
  69744. }
  69745. }
  69746. else {
  69747. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69748. callback(-1);
  69749. }
  69750. };
  69751. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69752. var _this = this;
  69753. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69754. try {
  69755. // Open a transaction to the database
  69756. var transaction = this.db.transaction(["versions"], "readwrite");
  69757. // the transaction could abort because of a QuotaExceededError error
  69758. transaction.onabort = function (event) {
  69759. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69760. var error = event.srcElement['error'];
  69761. if (error && error.name === "QuotaExceededError") {
  69762. _this.hasReachedQuota = true;
  69763. }
  69764. }
  69765. catch (ex) { }
  69766. callback(-1);
  69767. };
  69768. transaction.oncomplete = function (event) {
  69769. callback(_this.manifestVersionFound);
  69770. };
  69771. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69772. // Put the scene into the database
  69773. var addRequest = transaction.objectStore("versions").put(newVersion);
  69774. addRequest.onsuccess = function (event) {
  69775. };
  69776. addRequest.onerror = function (event) {
  69777. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69778. };
  69779. }
  69780. catch (ex) {
  69781. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69782. callback(-1);
  69783. }
  69784. }
  69785. else {
  69786. callback(-1);
  69787. }
  69788. };
  69789. /**
  69790. * Loads a file from database
  69791. * @param url defines the URL to load from
  69792. * @param sceneLoaded defines a callback to call on success
  69793. * @param progressCallBack defines a callback to call when progress changed
  69794. * @param errorCallback defines a callback to call on error
  69795. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69796. */
  69797. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69798. var _this = this;
  69799. var completeUrl = Database._ReturnFullUrlLocation(url);
  69800. var saveAndLoadFile = function () {
  69801. // the scene is not yet in the DB, let's try to save it
  69802. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69803. };
  69804. this._checkVersionFromDB(completeUrl, function (version) {
  69805. if (version !== -1) {
  69806. if (!_this.mustUpdateRessources) {
  69807. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69808. }
  69809. else {
  69810. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69811. }
  69812. }
  69813. else {
  69814. if (errorCallback) {
  69815. errorCallback();
  69816. }
  69817. }
  69818. });
  69819. };
  69820. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69821. if (this.isSupported && this.db) {
  69822. var targetStore;
  69823. if (url.indexOf(".babylon") !== -1) {
  69824. targetStore = "scenes";
  69825. }
  69826. else {
  69827. targetStore = "textures";
  69828. }
  69829. var file;
  69830. var transaction = this.db.transaction([targetStore]);
  69831. transaction.oncomplete = function (event) {
  69832. if (file) {
  69833. callback(file.data);
  69834. }
  69835. // file was not found in DB
  69836. else {
  69837. notInDBCallback();
  69838. }
  69839. };
  69840. transaction.onabort = function (event) {
  69841. notInDBCallback();
  69842. };
  69843. var getRequest = transaction.objectStore(targetStore).get(url);
  69844. getRequest.onsuccess = function (event) {
  69845. file = (event.target).result;
  69846. };
  69847. getRequest.onerror = function (event) {
  69848. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69849. notInDBCallback();
  69850. };
  69851. }
  69852. else {
  69853. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69854. callback();
  69855. }
  69856. };
  69857. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69858. var _this = this;
  69859. if (this.isSupported) {
  69860. var targetStore;
  69861. if (url.indexOf(".babylon") !== -1) {
  69862. targetStore = "scenes";
  69863. }
  69864. else {
  69865. targetStore = "textures";
  69866. }
  69867. // Create XHR
  69868. var xhr = new XMLHttpRequest();
  69869. var fileData;
  69870. xhr.open("GET", url, true);
  69871. if (useArrayBuffer) {
  69872. xhr.responseType = "arraybuffer";
  69873. }
  69874. if (progressCallback) {
  69875. xhr.onprogress = progressCallback;
  69876. }
  69877. xhr.addEventListener("load", function () {
  69878. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69879. // Blob as response (XHR2)
  69880. //fileData = xhr.responseText;
  69881. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69882. if (!_this.hasReachedQuota && _this.db) {
  69883. // Open a transaction to the database
  69884. var transaction = _this.db.transaction([targetStore], "readwrite");
  69885. // the transaction could abort because of a QuotaExceededError error
  69886. transaction.onabort = function (event) {
  69887. try {
  69888. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69889. var error = event.srcElement['error'];
  69890. if (error && error.name === "QuotaExceededError") {
  69891. _this.hasReachedQuota = true;
  69892. }
  69893. }
  69894. catch (ex) { }
  69895. callback(fileData);
  69896. };
  69897. transaction.oncomplete = function (event) {
  69898. callback(fileData);
  69899. };
  69900. var newFile;
  69901. if (targetStore === "scenes") {
  69902. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69903. }
  69904. else {
  69905. newFile = { textureUrl: url, data: fileData };
  69906. }
  69907. try {
  69908. // Put the scene into the database
  69909. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69910. addRequest.onsuccess = function (event) {
  69911. };
  69912. addRequest.onerror = function (event) {
  69913. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69914. };
  69915. }
  69916. catch (ex) {
  69917. callback(fileData);
  69918. }
  69919. }
  69920. else {
  69921. callback(fileData);
  69922. }
  69923. }
  69924. else {
  69925. callback();
  69926. }
  69927. }, false);
  69928. xhr.addEventListener("error", function (event) {
  69929. BABYLON.Tools.Error("error on XHR request.");
  69930. callback();
  69931. }, false);
  69932. xhr.send();
  69933. }
  69934. else {
  69935. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69936. callback();
  69937. }
  69938. };
  69939. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69940. Database.IsUASupportingBlobStorage = true;
  69941. /** Gets a boolean indicating if Database storate is enabled */
  69942. Database.IDBStorageEnabled = true;
  69943. Database._ParseURL = function (url) {
  69944. var a = document.createElement('a');
  69945. a.href = url;
  69946. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69947. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69948. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69949. return absLocation;
  69950. };
  69951. Database._ReturnFullUrlLocation = function (url) {
  69952. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69953. return (Database._ParseURL(window.location.href) + url);
  69954. }
  69955. else {
  69956. return url;
  69957. }
  69958. };
  69959. return Database;
  69960. }());
  69961. BABYLON.Database = Database;
  69962. })(BABYLON || (BABYLON = {}));
  69963. //# sourceMappingURL=babylon.database.js.map
  69964. var BABYLON;
  69965. (function (BABYLON) {
  69966. var FresnelParameters = /** @class */ (function () {
  69967. function FresnelParameters() {
  69968. this._isEnabled = true;
  69969. this.leftColor = BABYLON.Color3.White();
  69970. this.rightColor = BABYLON.Color3.Black();
  69971. this.bias = 0;
  69972. this.power = 1;
  69973. }
  69974. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69975. get: function () {
  69976. return this._isEnabled;
  69977. },
  69978. set: function (value) {
  69979. if (this._isEnabled === value) {
  69980. return;
  69981. }
  69982. this._isEnabled = value;
  69983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69984. },
  69985. enumerable: true,
  69986. configurable: true
  69987. });
  69988. FresnelParameters.prototype.clone = function () {
  69989. var newFresnelParameters = new FresnelParameters();
  69990. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69991. return newFresnelParameters;
  69992. };
  69993. FresnelParameters.prototype.serialize = function () {
  69994. var serializationObject = {};
  69995. serializationObject.isEnabled = this.isEnabled;
  69996. serializationObject.leftColor = this.leftColor.asArray();
  69997. serializationObject.rightColor = this.rightColor.asArray();
  69998. serializationObject.bias = this.bias;
  69999. serializationObject.power = this.power;
  70000. return serializationObject;
  70001. };
  70002. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70003. var fresnelParameters = new FresnelParameters();
  70004. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70005. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70006. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70007. fresnelParameters.bias = parsedFresnelParameters.bias;
  70008. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70009. return fresnelParameters;
  70010. };
  70011. return FresnelParameters;
  70012. }());
  70013. BABYLON.FresnelParameters = FresnelParameters;
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70016. var BABYLON;
  70017. (function (BABYLON) {
  70018. var MultiMaterial = /** @class */ (function (_super) {
  70019. __extends(MultiMaterial, _super);
  70020. function MultiMaterial(name, scene) {
  70021. var _this = _super.call(this, name, scene, true) || this;
  70022. scene.multiMaterials.push(_this);
  70023. _this.subMaterials = new Array();
  70024. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70025. return _this;
  70026. }
  70027. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70028. get: function () {
  70029. return this._subMaterials;
  70030. },
  70031. set: function (value) {
  70032. this._subMaterials = value;
  70033. this._hookArray(value);
  70034. },
  70035. enumerable: true,
  70036. configurable: true
  70037. });
  70038. MultiMaterial.prototype._hookArray = function (array) {
  70039. var _this = this;
  70040. var oldPush = array.push;
  70041. array.push = function () {
  70042. var items = [];
  70043. for (var _i = 0; _i < arguments.length; _i++) {
  70044. items[_i] = arguments[_i];
  70045. }
  70046. var result = oldPush.apply(array, items);
  70047. _this._markAllSubMeshesAsTexturesDirty();
  70048. return result;
  70049. };
  70050. var oldSplice = array.splice;
  70051. array.splice = function (index, deleteCount) {
  70052. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70053. _this._markAllSubMeshesAsTexturesDirty();
  70054. return deleted;
  70055. };
  70056. };
  70057. // Properties
  70058. MultiMaterial.prototype.getSubMaterial = function (index) {
  70059. if (index < 0 || index >= this.subMaterials.length) {
  70060. return this.getScene().defaultMaterial;
  70061. }
  70062. return this.subMaterials[index];
  70063. };
  70064. MultiMaterial.prototype.getActiveTextures = function () {
  70065. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70066. if (subMaterial) {
  70067. return subMaterial.getActiveTextures();
  70068. }
  70069. else {
  70070. return [];
  70071. }
  70072. }));
  70073. var _a;
  70074. };
  70075. // Methods
  70076. MultiMaterial.prototype.getClassName = function () {
  70077. return "MultiMaterial";
  70078. };
  70079. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70080. for (var index = 0; index < this.subMaterials.length; index++) {
  70081. var subMaterial = this.subMaterials[index];
  70082. if (subMaterial) {
  70083. if (subMaterial.storeEffectOnSubMeshes) {
  70084. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70085. return false;
  70086. }
  70087. continue;
  70088. }
  70089. if (!subMaterial.isReady(mesh)) {
  70090. return false;
  70091. }
  70092. }
  70093. }
  70094. return true;
  70095. };
  70096. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70097. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70098. for (var index = 0; index < this.subMaterials.length; index++) {
  70099. var subMaterial = null;
  70100. var current = this.subMaterials[index];
  70101. if (cloneChildren && current) {
  70102. subMaterial = current.clone(name + "-" + current.name);
  70103. }
  70104. else {
  70105. subMaterial = this.subMaterials[index];
  70106. }
  70107. newMultiMaterial.subMaterials.push(subMaterial);
  70108. }
  70109. return newMultiMaterial;
  70110. };
  70111. MultiMaterial.prototype.serialize = function () {
  70112. var serializationObject = {};
  70113. serializationObject.name = this.name;
  70114. serializationObject.id = this.id;
  70115. if (BABYLON.Tags) {
  70116. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70117. }
  70118. serializationObject.materials = [];
  70119. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70120. var subMat = this.subMaterials[matIndex];
  70121. if (subMat) {
  70122. serializationObject.materials.push(subMat.id);
  70123. }
  70124. else {
  70125. serializationObject.materials.push(null);
  70126. }
  70127. }
  70128. return serializationObject;
  70129. };
  70130. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70131. var scene = this.getScene();
  70132. if (!scene) {
  70133. return;
  70134. }
  70135. var index = scene.multiMaterials.indexOf(this);
  70136. if (index >= 0) {
  70137. scene.multiMaterials.splice(index, 1);
  70138. }
  70139. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70140. };
  70141. return MultiMaterial;
  70142. }(BABYLON.Material));
  70143. BABYLON.MultiMaterial = MultiMaterial;
  70144. })(BABYLON || (BABYLON = {}));
  70145. //# sourceMappingURL=babylon.multiMaterial.js.map
  70146. var BABYLON;
  70147. (function (BABYLON) {
  70148. var FreeCameraTouchInput = /** @class */ (function () {
  70149. function FreeCameraTouchInput() {
  70150. this._offsetX = null;
  70151. this._offsetY = null;
  70152. this._pointerPressed = new Array();
  70153. this.touchAngularSensibility = 200000.0;
  70154. this.touchMoveSensibility = 250.0;
  70155. }
  70156. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70157. var _this = this;
  70158. var previousPosition = null;
  70159. if (this._pointerInput === undefined) {
  70160. this._onLostFocus = function (evt) {
  70161. _this._offsetX = null;
  70162. _this._offsetY = null;
  70163. };
  70164. this._pointerInput = function (p, s) {
  70165. var evt = p.event;
  70166. if (evt.pointerType === "mouse") {
  70167. return;
  70168. }
  70169. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70170. if (!noPreventDefault) {
  70171. evt.preventDefault();
  70172. }
  70173. _this._pointerPressed.push(evt.pointerId);
  70174. if (_this._pointerPressed.length !== 1) {
  70175. return;
  70176. }
  70177. previousPosition = {
  70178. x: evt.clientX,
  70179. y: evt.clientY
  70180. };
  70181. }
  70182. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70183. if (!noPreventDefault) {
  70184. evt.preventDefault();
  70185. }
  70186. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70187. if (index === -1) {
  70188. return;
  70189. }
  70190. _this._pointerPressed.splice(index, 1);
  70191. if (index != 0) {
  70192. return;
  70193. }
  70194. previousPosition = null;
  70195. _this._offsetX = null;
  70196. _this._offsetY = null;
  70197. }
  70198. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70199. if (!noPreventDefault) {
  70200. evt.preventDefault();
  70201. }
  70202. if (!previousPosition) {
  70203. return;
  70204. }
  70205. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70206. if (index != 0) {
  70207. return;
  70208. }
  70209. _this._offsetX = evt.clientX - previousPosition.x;
  70210. _this._offsetY = -(evt.clientY - previousPosition.y);
  70211. }
  70212. };
  70213. }
  70214. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70215. if (this._onLostFocus) {
  70216. element.addEventListener("blur", this._onLostFocus);
  70217. }
  70218. };
  70219. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70220. if (this._pointerInput && element) {
  70221. if (this._observer) {
  70222. this.camera.getScene().onPointerObservable.remove(this._observer);
  70223. this._observer = null;
  70224. }
  70225. if (this._onLostFocus) {
  70226. element.removeEventListener("blur", this._onLostFocus);
  70227. this._onLostFocus = null;
  70228. }
  70229. this._pointerPressed = [];
  70230. this._offsetX = null;
  70231. this._offsetY = null;
  70232. }
  70233. };
  70234. FreeCameraTouchInput.prototype.checkInputs = function () {
  70235. if (this._offsetX && this._offsetY) {
  70236. var camera = this.camera;
  70237. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70238. if (this._pointerPressed.length > 1) {
  70239. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70240. }
  70241. else {
  70242. var speed = camera._computeLocalCameraSpeed();
  70243. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70244. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70245. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70246. }
  70247. }
  70248. };
  70249. FreeCameraTouchInput.prototype.getClassName = function () {
  70250. return "FreeCameraTouchInput";
  70251. };
  70252. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70253. return "touch";
  70254. };
  70255. __decorate([
  70256. BABYLON.serialize()
  70257. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70258. __decorate([
  70259. BABYLON.serialize()
  70260. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70261. return FreeCameraTouchInput;
  70262. }());
  70263. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70264. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70265. })(BABYLON || (BABYLON = {}));
  70266. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70267. var BABYLON;
  70268. (function (BABYLON) {
  70269. // We're mainly based on the logic defined into the FreeCamera code
  70270. var TouchCamera = /** @class */ (function (_super) {
  70271. __extends(TouchCamera, _super);
  70272. //-- end properties for backward compatibility for inputs
  70273. function TouchCamera(name, position, scene) {
  70274. var _this = _super.call(this, name, position, scene) || this;
  70275. _this.inputs.addTouch();
  70276. _this._setupInputs();
  70277. return _this;
  70278. }
  70279. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70280. //-- Begin properties for backward compatibility for inputs
  70281. get: function () {
  70282. var touch = this.inputs.attached["touch"];
  70283. if (touch)
  70284. return touch.touchAngularSensibility;
  70285. return 0;
  70286. },
  70287. set: function (value) {
  70288. var touch = this.inputs.attached["touch"];
  70289. if (touch)
  70290. touch.touchAngularSensibility = value;
  70291. },
  70292. enumerable: true,
  70293. configurable: true
  70294. });
  70295. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70296. get: function () {
  70297. var touch = this.inputs.attached["touch"];
  70298. if (touch)
  70299. return touch.touchMoveSensibility;
  70300. return 0;
  70301. },
  70302. set: function (value) {
  70303. var touch = this.inputs.attached["touch"];
  70304. if (touch)
  70305. touch.touchMoveSensibility = value;
  70306. },
  70307. enumerable: true,
  70308. configurable: true
  70309. });
  70310. TouchCamera.prototype.getClassName = function () {
  70311. return "TouchCamera";
  70312. };
  70313. TouchCamera.prototype._setupInputs = function () {
  70314. var mouse = this.inputs.attached["mouse"];
  70315. if (mouse) {
  70316. mouse.touchEnabled = false;
  70317. }
  70318. };
  70319. return TouchCamera;
  70320. }(BABYLON.FreeCamera));
  70321. BABYLON.TouchCamera = TouchCamera;
  70322. })(BABYLON || (BABYLON = {}));
  70323. //# sourceMappingURL=babylon.touchCamera.js.map
  70324. var BABYLON;
  70325. (function (BABYLON) {
  70326. var ProceduralTexture = /** @class */ (function (_super) {
  70327. __extends(ProceduralTexture, _super);
  70328. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70329. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70330. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70331. if (isCube === void 0) { isCube = false; }
  70332. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70333. _this.isCube = isCube;
  70334. _this.isEnabled = true;
  70335. _this._currentRefreshId = -1;
  70336. _this._refreshRate = 1;
  70337. _this._vertexBuffers = {};
  70338. _this._uniforms = new Array();
  70339. _this._samplers = new Array();
  70340. _this._textures = {};
  70341. _this._floats = {};
  70342. _this._floatsArrays = {};
  70343. _this._colors3 = {};
  70344. _this._colors4 = {};
  70345. _this._vectors2 = {};
  70346. _this._vectors3 = {};
  70347. _this._matrices = {};
  70348. _this._fallbackTextureUsed = false;
  70349. scene.proceduralTextures.push(_this);
  70350. _this._engine = scene.getEngine();
  70351. _this.name = name;
  70352. _this.isRenderTarget = true;
  70353. _this._size = size;
  70354. _this._generateMipMaps = generateMipMaps;
  70355. _this.setFragment(fragment);
  70356. _this._fallbackTexture = fallbackTexture;
  70357. if (isCube) {
  70358. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70359. _this.setFloat("face", 0);
  70360. }
  70361. else {
  70362. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70363. }
  70364. // VBO
  70365. var vertices = [];
  70366. vertices.push(1, 1);
  70367. vertices.push(-1, 1);
  70368. vertices.push(-1, -1);
  70369. vertices.push(1, -1);
  70370. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70371. _this._createIndexBuffer();
  70372. return _this;
  70373. }
  70374. ProceduralTexture.prototype._createIndexBuffer = function () {
  70375. var engine = this._engine;
  70376. // Indices
  70377. var indices = [];
  70378. indices.push(0);
  70379. indices.push(1);
  70380. indices.push(2);
  70381. indices.push(0);
  70382. indices.push(2);
  70383. indices.push(3);
  70384. this._indexBuffer = engine.createIndexBuffer(indices);
  70385. };
  70386. ProceduralTexture.prototype._rebuild = function () {
  70387. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70388. if (vb) {
  70389. vb._rebuild();
  70390. }
  70391. this._createIndexBuffer();
  70392. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70393. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70394. }
  70395. };
  70396. ProceduralTexture.prototype.reset = function () {
  70397. if (this._effect === undefined) {
  70398. return;
  70399. }
  70400. var engine = this._engine;
  70401. engine._releaseEffect(this._effect);
  70402. };
  70403. ProceduralTexture.prototype.isReady = function () {
  70404. var _this = this;
  70405. var engine = this._engine;
  70406. var shaders;
  70407. if (!this._fragment) {
  70408. return false;
  70409. }
  70410. if (this._fallbackTextureUsed) {
  70411. return true;
  70412. }
  70413. if (this._fragment.fragmentElement !== undefined) {
  70414. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70415. }
  70416. else {
  70417. shaders = { vertex: "procedural", fragment: this._fragment };
  70418. }
  70419. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70420. _this.releaseInternalTexture();
  70421. if (_this._fallbackTexture) {
  70422. _this._texture = _this._fallbackTexture._texture;
  70423. if (_this._texture) {
  70424. _this._texture.incrementReferences();
  70425. }
  70426. }
  70427. _this._fallbackTextureUsed = true;
  70428. });
  70429. return this._effect.isReady();
  70430. };
  70431. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70432. this._currentRefreshId = -1;
  70433. };
  70434. ProceduralTexture.prototype.setFragment = function (fragment) {
  70435. this._fragment = fragment;
  70436. };
  70437. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70438. get: function () {
  70439. return this._refreshRate;
  70440. },
  70441. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70442. set: function (value) {
  70443. this._refreshRate = value;
  70444. this.resetRefreshCounter();
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. ProceduralTexture.prototype._shouldRender = function () {
  70450. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70451. return false;
  70452. }
  70453. if (this._fallbackTextureUsed) {
  70454. return false;
  70455. }
  70456. if (this._currentRefreshId === -1) { // At least render once
  70457. this._currentRefreshId = 1;
  70458. return true;
  70459. }
  70460. if (this.refreshRate === this._currentRefreshId) {
  70461. this._currentRefreshId = 1;
  70462. return true;
  70463. }
  70464. this._currentRefreshId++;
  70465. return false;
  70466. };
  70467. ProceduralTexture.prototype.getRenderSize = function () {
  70468. return this._size;
  70469. };
  70470. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70471. if (this._fallbackTextureUsed) {
  70472. return;
  70473. }
  70474. this.releaseInternalTexture();
  70475. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70476. };
  70477. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70478. if (this._uniforms.indexOf(uniformName) === -1) {
  70479. this._uniforms.push(uniformName);
  70480. }
  70481. };
  70482. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70483. if (this._samplers.indexOf(name) === -1) {
  70484. this._samplers.push(name);
  70485. }
  70486. this._textures[name] = texture;
  70487. return this;
  70488. };
  70489. ProceduralTexture.prototype.setFloat = function (name, value) {
  70490. this._checkUniform(name);
  70491. this._floats[name] = value;
  70492. return this;
  70493. };
  70494. ProceduralTexture.prototype.setFloats = function (name, value) {
  70495. this._checkUniform(name);
  70496. this._floatsArrays[name] = value;
  70497. return this;
  70498. };
  70499. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70500. this._checkUniform(name);
  70501. this._colors3[name] = value;
  70502. return this;
  70503. };
  70504. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70505. this._checkUniform(name);
  70506. this._colors4[name] = value;
  70507. return this;
  70508. };
  70509. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70510. this._checkUniform(name);
  70511. this._vectors2[name] = value;
  70512. return this;
  70513. };
  70514. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70515. this._checkUniform(name);
  70516. this._vectors3[name] = value;
  70517. return this;
  70518. };
  70519. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70520. this._checkUniform(name);
  70521. this._matrices[name] = value;
  70522. return this;
  70523. };
  70524. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70525. var scene = this.getScene();
  70526. if (!scene) {
  70527. return;
  70528. }
  70529. var engine = this._engine;
  70530. // Render
  70531. engine.enableEffect(this._effect);
  70532. engine.setState(false);
  70533. // Texture
  70534. for (var name in this._textures) {
  70535. this._effect.setTexture(name, this._textures[name]);
  70536. }
  70537. // Float
  70538. for (name in this._floats) {
  70539. this._effect.setFloat(name, this._floats[name]);
  70540. }
  70541. // Floats
  70542. for (name in this._floatsArrays) {
  70543. this._effect.setArray(name, this._floatsArrays[name]);
  70544. }
  70545. // Color3
  70546. for (name in this._colors3) {
  70547. this._effect.setColor3(name, this._colors3[name]);
  70548. }
  70549. // Color4
  70550. for (name in this._colors4) {
  70551. var color = this._colors4[name];
  70552. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70553. }
  70554. // Vector2
  70555. for (name in this._vectors2) {
  70556. this._effect.setVector2(name, this._vectors2[name]);
  70557. }
  70558. // Vector3
  70559. for (name in this._vectors3) {
  70560. this._effect.setVector3(name, this._vectors3[name]);
  70561. }
  70562. // Matrix
  70563. for (name in this._matrices) {
  70564. this._effect.setMatrix(name, this._matrices[name]);
  70565. }
  70566. if (!this._texture) {
  70567. return;
  70568. }
  70569. if (this.isCube) {
  70570. for (var face = 0; face < 6; face++) {
  70571. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70572. // VBOs
  70573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70574. this._effect.setFloat("face", face);
  70575. // Clear
  70576. engine.clear(scene.clearColor, true, true, true);
  70577. // Draw order
  70578. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70579. // Mipmaps
  70580. if (face === 5) {
  70581. engine.generateMipMapsForCubemap(this._texture);
  70582. }
  70583. }
  70584. }
  70585. else {
  70586. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70587. // VBOs
  70588. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70589. // Clear
  70590. engine.clear(scene.clearColor, true, true, true);
  70591. // Draw order
  70592. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70593. }
  70594. // Unbind
  70595. engine.unBindFramebuffer(this._texture, this.isCube);
  70596. if (this.onGenerated) {
  70597. this.onGenerated();
  70598. }
  70599. };
  70600. ProceduralTexture.prototype.clone = function () {
  70601. var textureSize = this.getSize();
  70602. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70603. // Base texture
  70604. newTexture.hasAlpha = this.hasAlpha;
  70605. newTexture.level = this.level;
  70606. // RenderTarget Texture
  70607. newTexture.coordinatesMode = this.coordinatesMode;
  70608. return newTexture;
  70609. };
  70610. ProceduralTexture.prototype.dispose = function () {
  70611. var scene = this.getScene();
  70612. if (!scene) {
  70613. return;
  70614. }
  70615. var index = scene.proceduralTextures.indexOf(this);
  70616. if (index >= 0) {
  70617. scene.proceduralTextures.splice(index, 1);
  70618. }
  70619. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70620. if (vertexBuffer) {
  70621. vertexBuffer.dispose();
  70622. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70623. }
  70624. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70625. this._indexBuffer = null;
  70626. }
  70627. _super.prototype.dispose.call(this);
  70628. };
  70629. return ProceduralTexture;
  70630. }(BABYLON.Texture));
  70631. BABYLON.ProceduralTexture = ProceduralTexture;
  70632. })(BABYLON || (BABYLON = {}));
  70633. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70634. var BABYLON;
  70635. (function (BABYLON) {
  70636. var CustomProceduralTexture = /** @class */ (function (_super) {
  70637. __extends(CustomProceduralTexture, _super);
  70638. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70639. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70640. _this._animate = true;
  70641. _this._time = 0;
  70642. _this._texturePath = texturePath;
  70643. //Try to load json
  70644. _this.loadJson(texturePath);
  70645. _this.refreshRate = 1;
  70646. return _this;
  70647. }
  70648. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70649. var _this = this;
  70650. var noConfigFile = function () {
  70651. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70652. try {
  70653. _this.setFragment(_this._texturePath);
  70654. }
  70655. catch (ex) {
  70656. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70657. }
  70658. };
  70659. var configFileUrl = jsonUrl + "/config.json";
  70660. var xhr = new XMLHttpRequest();
  70661. xhr.open("GET", configFileUrl, true);
  70662. xhr.addEventListener("load", function () {
  70663. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70664. try {
  70665. _this._config = JSON.parse(xhr.response);
  70666. _this.updateShaderUniforms();
  70667. _this.updateTextures();
  70668. _this.setFragment(_this._texturePath + "/custom");
  70669. _this._animate = _this._config.animate;
  70670. _this.refreshRate = _this._config.refreshrate;
  70671. }
  70672. catch (ex) {
  70673. noConfigFile();
  70674. }
  70675. }
  70676. else {
  70677. noConfigFile();
  70678. }
  70679. }, false);
  70680. xhr.addEventListener("error", function () {
  70681. noConfigFile();
  70682. }, false);
  70683. try {
  70684. xhr.send();
  70685. }
  70686. catch (ex) {
  70687. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70688. }
  70689. };
  70690. CustomProceduralTexture.prototype.isReady = function () {
  70691. if (!_super.prototype.isReady.call(this)) {
  70692. return false;
  70693. }
  70694. for (var name in this._textures) {
  70695. var texture = this._textures[name];
  70696. if (!texture.isReady()) {
  70697. return false;
  70698. }
  70699. }
  70700. return true;
  70701. };
  70702. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70703. var scene = this.getScene();
  70704. if (this._animate && scene) {
  70705. this._time += scene.getAnimationRatio() * 0.03;
  70706. this.updateShaderUniforms();
  70707. }
  70708. _super.prototype.render.call(this, useCameraPostProcess);
  70709. };
  70710. CustomProceduralTexture.prototype.updateTextures = function () {
  70711. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70712. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70713. }
  70714. };
  70715. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70716. if (this._config) {
  70717. for (var j = 0; j < this._config.uniforms.length; j++) {
  70718. var uniform = this._config.uniforms[j];
  70719. switch (uniform.type) {
  70720. case "float":
  70721. this.setFloat(uniform.name, uniform.value);
  70722. break;
  70723. case "color3":
  70724. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70725. break;
  70726. case "color4":
  70727. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70728. break;
  70729. case "vector2":
  70730. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70731. break;
  70732. case "vector3":
  70733. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70734. break;
  70735. }
  70736. }
  70737. }
  70738. this.setFloat("time", this._time);
  70739. };
  70740. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70741. get: function () {
  70742. return this._animate;
  70743. },
  70744. set: function (value) {
  70745. this._animate = value;
  70746. },
  70747. enumerable: true,
  70748. configurable: true
  70749. });
  70750. return CustomProceduralTexture;
  70751. }(BABYLON.ProceduralTexture));
  70752. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70753. })(BABYLON || (BABYLON = {}));
  70754. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70755. var BABYLON;
  70756. (function (BABYLON) {
  70757. var FreeCameraGamepadInput = /** @class */ (function () {
  70758. function FreeCameraGamepadInput() {
  70759. this.gamepadAngularSensibility = 200;
  70760. this.gamepadMoveSensibility = 40;
  70761. // private members
  70762. this._cameraTransform = BABYLON.Matrix.Identity();
  70763. this._deltaTransform = BABYLON.Vector3.Zero();
  70764. this._vector3 = BABYLON.Vector3.Zero();
  70765. this._vector2 = BABYLON.Vector2.Zero();
  70766. }
  70767. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70768. var _this = this;
  70769. var manager = this.camera.getScene().gamepadManager;
  70770. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70771. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70772. // prioritize XBOX gamepads.
  70773. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70774. _this.gamepad = gamepad;
  70775. }
  70776. }
  70777. });
  70778. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70779. if (_this.gamepad === gamepad) {
  70780. _this.gamepad = null;
  70781. }
  70782. });
  70783. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70784. };
  70785. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70786. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70787. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70788. this.gamepad = null;
  70789. };
  70790. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70791. if (this.gamepad && this.gamepad.leftStick) {
  70792. var camera = this.camera;
  70793. var LSValues = this.gamepad.leftStick;
  70794. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70795. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70796. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70797. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70798. var RSValues = this.gamepad.rightStick;
  70799. if (RSValues) {
  70800. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70801. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70802. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70803. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70804. }
  70805. else {
  70806. RSValues = { x: 0, y: 0 };
  70807. }
  70808. if (!camera.rotationQuaternion) {
  70809. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70810. }
  70811. else {
  70812. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70813. }
  70814. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70815. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70816. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70817. camera.cameraDirection.addInPlace(this._deltaTransform);
  70818. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70819. camera.cameraRotation.addInPlace(this._vector2);
  70820. }
  70821. };
  70822. FreeCameraGamepadInput.prototype.getClassName = function () {
  70823. return "FreeCameraGamepadInput";
  70824. };
  70825. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70826. return "gamepad";
  70827. };
  70828. __decorate([
  70829. BABYLON.serialize()
  70830. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70831. __decorate([
  70832. BABYLON.serialize()
  70833. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70834. return FreeCameraGamepadInput;
  70835. }());
  70836. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70837. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70838. })(BABYLON || (BABYLON = {}));
  70839. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70840. var BABYLON;
  70841. (function (BABYLON) {
  70842. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70843. function ArcRotateCameraGamepadInput() {
  70844. this.gamepadRotationSensibility = 80;
  70845. this.gamepadMoveSensibility = 40;
  70846. }
  70847. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70848. var _this = this;
  70849. var manager = this.camera.getScene().gamepadManager;
  70850. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70851. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70852. // prioritize XBOX gamepads.
  70853. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70854. _this.gamepad = gamepad;
  70855. }
  70856. }
  70857. });
  70858. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70859. if (_this.gamepad === gamepad) {
  70860. _this.gamepad = null;
  70861. }
  70862. });
  70863. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70864. };
  70865. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70866. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70867. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70868. this.gamepad = null;
  70869. };
  70870. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70871. if (this.gamepad) {
  70872. var camera = this.camera;
  70873. var RSValues = this.gamepad.rightStick;
  70874. if (RSValues) {
  70875. if (RSValues.x != 0) {
  70876. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70877. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70878. camera.inertialAlphaOffset += normalizedRX;
  70879. }
  70880. }
  70881. if (RSValues.y != 0) {
  70882. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70883. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70884. camera.inertialBetaOffset += normalizedRY;
  70885. }
  70886. }
  70887. }
  70888. var LSValues = this.gamepad.leftStick;
  70889. if (LSValues && LSValues.y != 0) {
  70890. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70891. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70892. this.camera.inertialRadiusOffset -= normalizedLY;
  70893. }
  70894. }
  70895. }
  70896. };
  70897. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70898. return "ArcRotateCameraGamepadInput";
  70899. };
  70900. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70901. return "gamepad";
  70902. };
  70903. __decorate([
  70904. BABYLON.serialize()
  70905. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70906. __decorate([
  70907. BABYLON.serialize()
  70908. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70909. return ArcRotateCameraGamepadInput;
  70910. }());
  70911. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70912. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70913. })(BABYLON || (BABYLON = {}));
  70914. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70915. var BABYLON;
  70916. (function (BABYLON) {
  70917. var GamepadManager = /** @class */ (function () {
  70918. function GamepadManager(_scene) {
  70919. var _this = this;
  70920. this._scene = _scene;
  70921. this._babylonGamepads = [];
  70922. this._oneGamepadConnected = false;
  70923. this._isMonitoring = false;
  70924. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70925. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70926. this._gamepadEventSupported = false;
  70927. }
  70928. else {
  70929. this._gamepadEventSupported = 'GamepadEvent' in window;
  70930. this._gamepadSupport = (navigator.getGamepads ||
  70931. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70932. }
  70933. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70934. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70935. for (var i in _this._babylonGamepads) {
  70936. var gamepad = _this._babylonGamepads[i];
  70937. if (gamepad && gamepad._isConnected) {
  70938. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70939. }
  70940. }
  70941. });
  70942. this._onGamepadConnectedEvent = function (evt) {
  70943. var gamepad = evt.gamepad;
  70944. if (gamepad.index in _this._babylonGamepads) {
  70945. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70946. return;
  70947. }
  70948. }
  70949. var newGamepad;
  70950. if (_this._babylonGamepads[gamepad.index]) {
  70951. newGamepad = _this._babylonGamepads[gamepad.index];
  70952. newGamepad.browserGamepad = gamepad;
  70953. newGamepad._isConnected = true;
  70954. }
  70955. else {
  70956. newGamepad = _this._addNewGamepad(gamepad);
  70957. }
  70958. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70959. _this._startMonitoringGamepads();
  70960. };
  70961. this._onGamepadDisconnectedEvent = function (evt) {
  70962. var gamepad = evt.gamepad;
  70963. // Remove the gamepad from the list of gamepads to monitor.
  70964. for (var i in _this._babylonGamepads) {
  70965. if (_this._babylonGamepads[i].index === gamepad.index) {
  70966. var disconnectedGamepad = _this._babylonGamepads[i];
  70967. disconnectedGamepad._isConnected = false;
  70968. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70969. break;
  70970. }
  70971. }
  70972. };
  70973. if (this._gamepadSupport) {
  70974. //first add already-connected gamepads
  70975. this._updateGamepadObjects();
  70976. if (this._babylonGamepads.length) {
  70977. this._startMonitoringGamepads();
  70978. }
  70979. // Checking if the gamepad connected event is supported (like in Firefox)
  70980. if (this._gamepadEventSupported) {
  70981. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70982. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70983. }
  70984. else {
  70985. this._startMonitoringGamepads();
  70986. }
  70987. }
  70988. }
  70989. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70990. get: function () {
  70991. return this._babylonGamepads;
  70992. },
  70993. enumerable: true,
  70994. configurable: true
  70995. });
  70996. GamepadManager.prototype.getGamepadByType = function (type) {
  70997. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70998. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70999. var gamepad = _a[_i];
  71000. if (gamepad && gamepad.type === type) {
  71001. return gamepad;
  71002. }
  71003. }
  71004. return null;
  71005. };
  71006. GamepadManager.prototype.dispose = function () {
  71007. if (this._gamepadEventSupported) {
  71008. if (this._onGamepadConnectedEvent) {
  71009. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71010. }
  71011. if (this._onGamepadDisconnectedEvent) {
  71012. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71013. }
  71014. this._onGamepadConnectedEvent = null;
  71015. this._onGamepadDisconnectedEvent = null;
  71016. }
  71017. this._babylonGamepads.forEach(function (gamepad) {
  71018. gamepad.dispose();
  71019. });
  71020. this.onGamepadConnectedObservable.clear();
  71021. this.onGamepadDisconnectedObservable.clear();
  71022. this._oneGamepadConnected = false;
  71023. this._stopMonitoringGamepads();
  71024. this._babylonGamepads = [];
  71025. };
  71026. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71027. if (!this._oneGamepadConnected) {
  71028. this._oneGamepadConnected = true;
  71029. }
  71030. var newGamepad;
  71031. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71032. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71033. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71034. }
  71035. // if pose is supported, use the (WebVR) pose enabled controller
  71036. else if (gamepad.pose) {
  71037. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71038. }
  71039. else {
  71040. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71041. }
  71042. this._babylonGamepads[newGamepad.index] = newGamepad;
  71043. return newGamepad;
  71044. };
  71045. GamepadManager.prototype._startMonitoringGamepads = function () {
  71046. if (!this._isMonitoring) {
  71047. this._isMonitoring = true;
  71048. //back-comp
  71049. if (!this._scene) {
  71050. this._checkGamepadsStatus();
  71051. }
  71052. }
  71053. };
  71054. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71055. this._isMonitoring = false;
  71056. };
  71057. GamepadManager.prototype._checkGamepadsStatus = function () {
  71058. var _this = this;
  71059. // Hack to be compatible Chrome
  71060. this._updateGamepadObjects();
  71061. for (var i in this._babylonGamepads) {
  71062. var gamepad = this._babylonGamepads[i];
  71063. if (!gamepad || !gamepad.isConnected) {
  71064. continue;
  71065. }
  71066. gamepad.update();
  71067. }
  71068. if (this._isMonitoring && !this._scene) {
  71069. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71070. }
  71071. };
  71072. // This function is called only on Chrome, which does not properly support
  71073. // connection/disconnection events and forces you to recopy again the gamepad object
  71074. GamepadManager.prototype._updateGamepadObjects = function () {
  71075. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71076. for (var i = 0; i < gamepads.length; i++) {
  71077. var gamepad = gamepads[i];
  71078. if (gamepad) {
  71079. if (!this._babylonGamepads[gamepad.index]) {
  71080. var newGamepad = this._addNewGamepad(gamepad);
  71081. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71082. }
  71083. else {
  71084. // Forced to copy again this object for Chrome for unknown reason
  71085. this._babylonGamepads[i].browserGamepad = gamepad;
  71086. if (!this._babylonGamepads[i].isConnected) {
  71087. this._babylonGamepads[i]._isConnected = true;
  71088. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71089. }
  71090. }
  71091. }
  71092. }
  71093. };
  71094. return GamepadManager;
  71095. }());
  71096. BABYLON.GamepadManager = GamepadManager;
  71097. })(BABYLON || (BABYLON = {}));
  71098. //# sourceMappingURL=babylon.gamepadManager.js.map
  71099. var BABYLON;
  71100. (function (BABYLON) {
  71101. var StickValues = /** @class */ (function () {
  71102. function StickValues(x, y) {
  71103. this.x = x;
  71104. this.y = y;
  71105. }
  71106. return StickValues;
  71107. }());
  71108. BABYLON.StickValues = StickValues;
  71109. var Gamepad = /** @class */ (function () {
  71110. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71111. if (leftStickX === void 0) { leftStickX = 0; }
  71112. if (leftStickY === void 0) { leftStickY = 1; }
  71113. if (rightStickX === void 0) { rightStickX = 2; }
  71114. if (rightStickY === void 0) { rightStickY = 3; }
  71115. this.id = id;
  71116. this.index = index;
  71117. this.browserGamepad = browserGamepad;
  71118. this._isConnected = true;
  71119. this._invertLeftStickY = false;
  71120. this.type = Gamepad.GAMEPAD;
  71121. this._leftStickAxisX = leftStickX;
  71122. this._leftStickAxisY = leftStickY;
  71123. this._rightStickAxisX = rightStickX;
  71124. this._rightStickAxisY = rightStickY;
  71125. if (this.browserGamepad.axes.length >= 2) {
  71126. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71127. }
  71128. if (this.browserGamepad.axes.length >= 4) {
  71129. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71130. }
  71131. }
  71132. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71133. get: function () {
  71134. return this._isConnected;
  71135. },
  71136. enumerable: true,
  71137. configurable: true
  71138. });
  71139. Gamepad.prototype.onleftstickchanged = function (callback) {
  71140. this._onleftstickchanged = callback;
  71141. };
  71142. Gamepad.prototype.onrightstickchanged = function (callback) {
  71143. this._onrightstickchanged = callback;
  71144. };
  71145. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71146. get: function () {
  71147. return this._leftStick;
  71148. },
  71149. set: function (newValues) {
  71150. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71151. this._onleftstickchanged(newValues);
  71152. }
  71153. this._leftStick = newValues;
  71154. },
  71155. enumerable: true,
  71156. configurable: true
  71157. });
  71158. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71159. get: function () {
  71160. return this._rightStick;
  71161. },
  71162. set: function (newValues) {
  71163. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71164. this._onrightstickchanged(newValues);
  71165. }
  71166. this._rightStick = newValues;
  71167. },
  71168. enumerable: true,
  71169. configurable: true
  71170. });
  71171. Gamepad.prototype.update = function () {
  71172. if (this._leftStick) {
  71173. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71174. if (this._invertLeftStickY) {
  71175. this.leftStick.y *= -1;
  71176. }
  71177. }
  71178. if (this._rightStick) {
  71179. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71180. }
  71181. };
  71182. Gamepad.prototype.dispose = function () {
  71183. };
  71184. Gamepad.GAMEPAD = 0;
  71185. Gamepad.GENERIC = 1;
  71186. Gamepad.XBOX = 2;
  71187. Gamepad.POSE_ENABLED = 3;
  71188. return Gamepad;
  71189. }());
  71190. BABYLON.Gamepad = Gamepad;
  71191. var GenericPad = /** @class */ (function (_super) {
  71192. __extends(GenericPad, _super);
  71193. function GenericPad(id, index, browserGamepad) {
  71194. var _this = _super.call(this, id, index, browserGamepad) || this;
  71195. _this.onButtonDownObservable = new BABYLON.Observable();
  71196. _this.onButtonUpObservable = new BABYLON.Observable();
  71197. _this.type = Gamepad.GENERIC;
  71198. _this._buttons = new Array(browserGamepad.buttons.length);
  71199. return _this;
  71200. }
  71201. GenericPad.prototype.onbuttondown = function (callback) {
  71202. this._onbuttondown = callback;
  71203. };
  71204. GenericPad.prototype.onbuttonup = function (callback) {
  71205. this._onbuttonup = callback;
  71206. };
  71207. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71208. if (newValue !== currentValue) {
  71209. if (newValue === 1) {
  71210. if (this._onbuttondown) {
  71211. this._onbuttondown(buttonIndex);
  71212. }
  71213. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71214. }
  71215. if (newValue === 0) {
  71216. if (this._onbuttonup) {
  71217. this._onbuttonup(buttonIndex);
  71218. }
  71219. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71220. }
  71221. }
  71222. return newValue;
  71223. };
  71224. GenericPad.prototype.update = function () {
  71225. _super.prototype.update.call(this);
  71226. for (var index = 0; index < this._buttons.length; index++) {
  71227. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71228. }
  71229. };
  71230. GenericPad.prototype.dispose = function () {
  71231. _super.prototype.dispose.call(this);
  71232. this.onButtonDownObservable.clear();
  71233. this.onButtonUpObservable.clear();
  71234. };
  71235. return GenericPad;
  71236. }(Gamepad));
  71237. BABYLON.GenericPad = GenericPad;
  71238. })(BABYLON || (BABYLON = {}));
  71239. //# sourceMappingURL=babylon.gamepad.js.map
  71240. var BABYLON;
  71241. (function (BABYLON) {
  71242. /**
  71243. * Defines supported buttons for XBox360 compatible gamepads
  71244. */
  71245. var Xbox360Button;
  71246. (function (Xbox360Button) {
  71247. /** A */
  71248. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71249. /** B */
  71250. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71251. /** X */
  71252. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71253. /** Y */
  71254. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71255. /** Start */
  71256. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71257. /** Back */
  71258. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71259. /** Left button */
  71260. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71261. /** Right button */
  71262. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71263. /** Left stick */
  71264. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71265. /** Right stick */
  71266. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71267. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71268. /** Defines values for XBox360 DPad */
  71269. var Xbox360Dpad;
  71270. (function (Xbox360Dpad) {
  71271. /** Up */
  71272. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71273. /** Down */
  71274. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71275. /** Left */
  71276. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71277. /** Right */
  71278. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71279. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71280. /**
  71281. * Defines a XBox360 gamepad
  71282. */
  71283. var Xbox360Pad = /** @class */ (function (_super) {
  71284. __extends(Xbox360Pad, _super);
  71285. /**
  71286. * Creates a new XBox360 gamepad object
  71287. * @param id defines the id of this gamepad
  71288. * @param index defines its index
  71289. * @param gamepad defines the internal HTML gamepad object
  71290. * @param xboxOne defines if it is a XBox One gamepad
  71291. */
  71292. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71293. if (xboxOne === void 0) { xboxOne = false; }
  71294. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71295. _this._leftTrigger = 0;
  71296. _this._rightTrigger = 0;
  71297. /** Observable raised when a button is pressed */
  71298. _this.onButtonDownObservable = new BABYLON.Observable();
  71299. /** Observable raised when a button is released */
  71300. _this.onButtonUpObservable = new BABYLON.Observable();
  71301. /** Observable raised when a pad is pressed */
  71302. _this.onPadDownObservable = new BABYLON.Observable();
  71303. /** Observable raised when a pad is released */
  71304. _this.onPadUpObservable = new BABYLON.Observable();
  71305. _this._buttonA = 0;
  71306. _this._buttonB = 0;
  71307. _this._buttonX = 0;
  71308. _this._buttonY = 0;
  71309. _this._buttonBack = 0;
  71310. _this._buttonStart = 0;
  71311. _this._buttonLB = 0;
  71312. _this._buttonRB = 0;
  71313. _this._buttonLeftStick = 0;
  71314. _this._buttonRightStick = 0;
  71315. _this._dPadUp = 0;
  71316. _this._dPadDown = 0;
  71317. _this._dPadLeft = 0;
  71318. _this._dPadRight = 0;
  71319. _this._isXboxOnePad = false;
  71320. _this.type = BABYLON.Gamepad.XBOX;
  71321. _this._isXboxOnePad = xboxOne;
  71322. return _this;
  71323. }
  71324. /**
  71325. * Defines the callback to call when left trigger is pressed
  71326. * @param callback defines the callback to use
  71327. */
  71328. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71329. this._onlefttriggerchanged = callback;
  71330. };
  71331. /**
  71332. * Defines the callback to call when right trigger is pressed
  71333. * @param callback defines the callback to use
  71334. */
  71335. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71336. this._onrighttriggerchanged = callback;
  71337. };
  71338. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71339. /**
  71340. * Gets or sets left trigger value
  71341. */
  71342. get: function () {
  71343. return this._leftTrigger;
  71344. },
  71345. set: function (newValue) {
  71346. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71347. this._onlefttriggerchanged(newValue);
  71348. }
  71349. this._leftTrigger = newValue;
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71355. /**
  71356. * Gets or sets right trigger value
  71357. */
  71358. get: function () {
  71359. return this._rightTrigger;
  71360. },
  71361. set: function (newValue) {
  71362. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71363. this._onrighttriggerchanged(newValue);
  71364. }
  71365. this._rightTrigger = newValue;
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. /**
  71371. * Defines the callback to call when a button is pressed
  71372. * @param callback defines the callback to use
  71373. */
  71374. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71375. this._onbuttondown = callback;
  71376. };
  71377. /**
  71378. * Defines the callback to call when a button is released
  71379. * @param callback defines the callback to use
  71380. */
  71381. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71382. this._onbuttonup = callback;
  71383. };
  71384. /**
  71385. * Defines the callback to call when a pad is pressed
  71386. * @param callback defines the callback to use
  71387. */
  71388. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71389. this._ondpaddown = callback;
  71390. };
  71391. /**
  71392. * Defines the callback to call when a pad is released
  71393. * @param callback defines the callback to use
  71394. */
  71395. Xbox360Pad.prototype.ondpadup = function (callback) {
  71396. this._ondpadup = callback;
  71397. };
  71398. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71399. if (newValue !== currentValue) {
  71400. if (newValue === 1) {
  71401. if (this._onbuttondown) {
  71402. this._onbuttondown(buttonType);
  71403. }
  71404. this.onButtonDownObservable.notifyObservers(buttonType);
  71405. }
  71406. if (newValue === 0) {
  71407. if (this._onbuttonup) {
  71408. this._onbuttonup(buttonType);
  71409. }
  71410. this.onButtonUpObservable.notifyObservers(buttonType);
  71411. }
  71412. }
  71413. return newValue;
  71414. };
  71415. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71416. if (newValue !== currentValue) {
  71417. if (newValue === 1) {
  71418. if (this._ondpaddown) {
  71419. this._ondpaddown(buttonType);
  71420. }
  71421. this.onPadDownObservable.notifyObservers(buttonType);
  71422. }
  71423. if (newValue === 0) {
  71424. if (this._ondpadup) {
  71425. this._ondpadup(buttonType);
  71426. }
  71427. this.onPadUpObservable.notifyObservers(buttonType);
  71428. }
  71429. }
  71430. return newValue;
  71431. };
  71432. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71433. /** Gets or sets value of A button */
  71434. get: function () {
  71435. return this._buttonA;
  71436. },
  71437. set: function (value) {
  71438. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71439. },
  71440. enumerable: true,
  71441. configurable: true
  71442. });
  71443. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71444. /** Gets or sets value of B button */
  71445. get: function () {
  71446. return this._buttonB;
  71447. },
  71448. set: function (value) {
  71449. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71450. },
  71451. enumerable: true,
  71452. configurable: true
  71453. });
  71454. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71455. /** Gets or sets value of X button */
  71456. get: function () {
  71457. return this._buttonX;
  71458. },
  71459. set: function (value) {
  71460. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71461. },
  71462. enumerable: true,
  71463. configurable: true
  71464. });
  71465. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71466. /** Gets or sets value of Y button */
  71467. get: function () {
  71468. return this._buttonY;
  71469. },
  71470. set: function (value) {
  71471. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71472. },
  71473. enumerable: true,
  71474. configurable: true
  71475. });
  71476. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71477. /** Gets or sets value of Start button */
  71478. get: function () {
  71479. return this._buttonStart;
  71480. },
  71481. set: function (value) {
  71482. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71483. },
  71484. enumerable: true,
  71485. configurable: true
  71486. });
  71487. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71488. /** Gets or sets value of Back button */
  71489. get: function () {
  71490. return this._buttonBack;
  71491. },
  71492. set: function (value) {
  71493. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71494. },
  71495. enumerable: true,
  71496. configurable: true
  71497. });
  71498. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71499. /** Gets or sets value of Left button */
  71500. get: function () {
  71501. return this._buttonLB;
  71502. },
  71503. set: function (value) {
  71504. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71505. },
  71506. enumerable: true,
  71507. configurable: true
  71508. });
  71509. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71510. /** Gets or sets value of Right button */
  71511. get: function () {
  71512. return this._buttonRB;
  71513. },
  71514. set: function (value) {
  71515. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71516. },
  71517. enumerable: true,
  71518. configurable: true
  71519. });
  71520. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71521. /** Gets or sets value of left stick */
  71522. get: function () {
  71523. return this._buttonLeftStick;
  71524. },
  71525. set: function (value) {
  71526. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71527. },
  71528. enumerable: true,
  71529. configurable: true
  71530. });
  71531. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71532. /** Gets or sets value of right stick */
  71533. get: function () {
  71534. return this._buttonRightStick;
  71535. },
  71536. set: function (value) {
  71537. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71538. },
  71539. enumerable: true,
  71540. configurable: true
  71541. });
  71542. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71543. /** Gets or sets value of DPad up */
  71544. get: function () {
  71545. return this._dPadUp;
  71546. },
  71547. set: function (value) {
  71548. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71549. },
  71550. enumerable: true,
  71551. configurable: true
  71552. });
  71553. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71554. /** Gets or sets value of DPad down */
  71555. get: function () {
  71556. return this._dPadDown;
  71557. },
  71558. set: function (value) {
  71559. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71560. },
  71561. enumerable: true,
  71562. configurable: true
  71563. });
  71564. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71565. /** Gets or sets value of DPad left */
  71566. get: function () {
  71567. return this._dPadLeft;
  71568. },
  71569. set: function (value) {
  71570. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71571. },
  71572. enumerable: true,
  71573. configurable: true
  71574. });
  71575. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71576. /** Gets or sets value of DPad right */
  71577. get: function () {
  71578. return this._dPadRight;
  71579. },
  71580. set: function (value) {
  71581. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71582. },
  71583. enumerable: true,
  71584. configurable: true
  71585. });
  71586. /**
  71587. * Force the gamepad to synchronize with device values
  71588. */
  71589. Xbox360Pad.prototype.update = function () {
  71590. _super.prototype.update.call(this);
  71591. if (this._isXboxOnePad) {
  71592. this.buttonA = this.browserGamepad.buttons[0].value;
  71593. this.buttonB = this.browserGamepad.buttons[1].value;
  71594. this.buttonX = this.browserGamepad.buttons[2].value;
  71595. this.buttonY = this.browserGamepad.buttons[3].value;
  71596. this.buttonLB = this.browserGamepad.buttons[4].value;
  71597. this.buttonRB = this.browserGamepad.buttons[5].value;
  71598. this.leftTrigger = this.browserGamepad.axes[2];
  71599. this.rightTrigger = this.browserGamepad.axes[5];
  71600. this.buttonBack = this.browserGamepad.buttons[9].value;
  71601. this.buttonStart = this.browserGamepad.buttons[8].value;
  71602. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71603. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71604. this.dPadUp = this.browserGamepad.buttons[11].value;
  71605. this.dPadDown = this.browserGamepad.buttons[12].value;
  71606. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71607. this.dPadRight = this.browserGamepad.buttons[14].value;
  71608. }
  71609. else {
  71610. this.buttonA = this.browserGamepad.buttons[0].value;
  71611. this.buttonB = this.browserGamepad.buttons[1].value;
  71612. this.buttonX = this.browserGamepad.buttons[2].value;
  71613. this.buttonY = this.browserGamepad.buttons[3].value;
  71614. this.buttonLB = this.browserGamepad.buttons[4].value;
  71615. this.buttonRB = this.browserGamepad.buttons[5].value;
  71616. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71617. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71618. this.buttonBack = this.browserGamepad.buttons[8].value;
  71619. this.buttonStart = this.browserGamepad.buttons[9].value;
  71620. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71621. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71622. this.dPadUp = this.browserGamepad.buttons[12].value;
  71623. this.dPadDown = this.browserGamepad.buttons[13].value;
  71624. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71625. this.dPadRight = this.browserGamepad.buttons[15].value;
  71626. }
  71627. };
  71628. Xbox360Pad.prototype.dispose = function () {
  71629. _super.prototype.dispose.call(this);
  71630. this.onButtonDownObservable.clear();
  71631. this.onButtonUpObservable.clear();
  71632. this.onPadDownObservable.clear();
  71633. this.onPadUpObservable.clear();
  71634. };
  71635. return Xbox360Pad;
  71636. }(BABYLON.Gamepad));
  71637. BABYLON.Xbox360Pad = Xbox360Pad;
  71638. })(BABYLON || (BABYLON = {}));
  71639. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71640. var BABYLON;
  71641. (function (BABYLON) {
  71642. /**
  71643. * Defines the types of pose enabled controllers that are supported
  71644. */
  71645. var PoseEnabledControllerType;
  71646. (function (PoseEnabledControllerType) {
  71647. /**
  71648. * HTC Vive
  71649. */
  71650. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71651. /**
  71652. * Oculus Rift
  71653. */
  71654. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71655. /**
  71656. * Windows mixed reality
  71657. */
  71658. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71659. /**
  71660. * Samsung gear VR
  71661. */
  71662. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71663. /**
  71664. * Google Daydream
  71665. */
  71666. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71667. /**
  71668. * Generic
  71669. */
  71670. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71671. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71672. /**
  71673. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71674. */
  71675. var PoseEnabledControllerHelper = /** @class */ (function () {
  71676. function PoseEnabledControllerHelper() {
  71677. }
  71678. /**
  71679. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71680. * @param vrGamepad the gamepad to initialized
  71681. * @returns a vr controller of the type the gamepad identified as
  71682. */
  71683. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71684. // Oculus Touch
  71685. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71686. return new BABYLON.OculusTouchController(vrGamepad);
  71687. }
  71688. // Windows Mixed Reality controllers
  71689. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71690. return new BABYLON.WindowsMotionController(vrGamepad);
  71691. }
  71692. // HTC Vive
  71693. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71694. return new BABYLON.ViveController(vrGamepad);
  71695. }
  71696. // Samsung/Oculus Gear VR or Oculus Go
  71697. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71698. return new BABYLON.GearVRController(vrGamepad);
  71699. }
  71700. // Google Daydream
  71701. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71702. return new BABYLON.DaydreamController(vrGamepad);
  71703. }
  71704. // Generic
  71705. else {
  71706. return new BABYLON.GenericController(vrGamepad);
  71707. }
  71708. };
  71709. return PoseEnabledControllerHelper;
  71710. }());
  71711. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71712. /**
  71713. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71714. */
  71715. var PoseEnabledController = /** @class */ (function (_super) {
  71716. __extends(PoseEnabledController, _super);
  71717. /**
  71718. * Creates a new PoseEnabledController from a gamepad
  71719. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71720. */
  71721. function PoseEnabledController(browserGamepad) {
  71722. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71723. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71724. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71725. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71726. /**
  71727. * The device position in babylon space
  71728. */
  71729. _this.devicePosition = BABYLON.Vector3.Zero();
  71730. /**
  71731. * The device rotation in babylon space
  71732. */
  71733. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71734. /**
  71735. * The scale factor of the device in babylon space
  71736. */
  71737. _this.deviceScaleFactor = 1;
  71738. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71739. /**
  71740. * Internal, matrix used to convert room space to babylon space
  71741. */
  71742. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71743. /**
  71744. * Node to be used when casting a ray from the controller
  71745. */
  71746. _this._pointingPoseNode = null;
  71747. _this._workingMatrix = BABYLON.Matrix.Identity();
  71748. /**
  71749. * @hidden
  71750. */
  71751. _this._meshAttachedObservable = new BABYLON.Observable();
  71752. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71753. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71754. _this.position = BABYLON.Vector3.Zero();
  71755. _this.rotationQuaternion = new BABYLON.Quaternion();
  71756. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71757. _this._calculatedRotation = new BABYLON.Quaternion();
  71758. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71759. return _this;
  71760. }
  71761. /**
  71762. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71763. */
  71764. PoseEnabledController.prototype.update = function () {
  71765. _super.prototype.update.call(this);
  71766. var pose = this.browserGamepad.pose;
  71767. this.updateFromDevice(pose);
  71768. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71769. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71770. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71771. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71772. if (this._mesh) {
  71773. this._mesh.position.copyFrom(this.devicePosition);
  71774. if (this._mesh.rotationQuaternion) {
  71775. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71776. }
  71777. }
  71778. };
  71779. /**
  71780. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71781. * @param poseData raw pose fromthe device
  71782. */
  71783. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71784. if (poseData) {
  71785. this.rawPose = poseData;
  71786. if (poseData.position) {
  71787. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71788. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71789. this._deviceRoomPosition.z *= -1;
  71790. }
  71791. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71792. this._calculatedPosition.addInPlace(this.position);
  71793. }
  71794. var pose = this.rawPose;
  71795. if (poseData.orientation && pose.orientation) {
  71796. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71797. if (this._mesh) {
  71798. if (this._mesh.getScene().useRightHandedSystem) {
  71799. this._deviceRoomRotationQuaternion.z *= -1;
  71800. this._deviceRoomRotationQuaternion.w *= -1;
  71801. }
  71802. else {
  71803. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71804. }
  71805. }
  71806. // if the camera is set, rotate to the camera's rotation
  71807. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71808. }
  71809. }
  71810. };
  71811. /**
  71812. * Attaches a mesh to the controller
  71813. * @param mesh the mesh to be attached
  71814. */
  71815. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71816. if (this._mesh) {
  71817. this._mesh.parent = null;
  71818. }
  71819. this._mesh = mesh;
  71820. if (this._poseControlledCamera) {
  71821. this._mesh.parent = this._poseControlledCamera;
  71822. }
  71823. if (!this._mesh.rotationQuaternion) {
  71824. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71825. }
  71826. this._meshAttachedObservable.notifyObservers(mesh);
  71827. };
  71828. /**
  71829. * Attaches the controllers mesh to a camera
  71830. * @param camera the camera the mesh should be attached to
  71831. */
  71832. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71833. this._poseControlledCamera = camera;
  71834. if (this._mesh) {
  71835. this._mesh.parent = this._poseControlledCamera;
  71836. }
  71837. };
  71838. /**
  71839. * Disposes of the controller
  71840. */
  71841. PoseEnabledController.prototype.dispose = function () {
  71842. if (this._mesh) {
  71843. this._mesh.dispose();
  71844. }
  71845. this._mesh = null;
  71846. _super.prototype.dispose.call(this);
  71847. };
  71848. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71849. /**
  71850. * The mesh that is attached to the controller
  71851. */
  71852. get: function () {
  71853. return this._mesh;
  71854. },
  71855. enumerable: true,
  71856. configurable: true
  71857. });
  71858. /**
  71859. * Gets the ray of the controller in the direction the controller is pointing
  71860. * @param length the length the resulting ray should be
  71861. * @returns a ray in the direction the controller is pointing
  71862. */
  71863. PoseEnabledController.prototype.getForwardRay = function (length) {
  71864. if (length === void 0) { length = 100; }
  71865. if (!this.mesh) {
  71866. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71867. }
  71868. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71869. var origin = m.getTranslation();
  71870. var forward = new BABYLON.Vector3(0, 0, -1);
  71871. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71872. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71873. return new BABYLON.Ray(origin, direction, length);
  71874. };
  71875. /**
  71876. * Name of the child mesh that can be used to cast a ray from the controller
  71877. */
  71878. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71879. return PoseEnabledController;
  71880. }(BABYLON.Gamepad));
  71881. BABYLON.PoseEnabledController = PoseEnabledController;
  71882. })(BABYLON || (BABYLON = {}));
  71883. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71884. var BABYLON;
  71885. (function (BABYLON) {
  71886. /**
  71887. * Defines the WebVRController object that represents controllers tracked in 3D space
  71888. */
  71889. var WebVRController = /** @class */ (function (_super) {
  71890. __extends(WebVRController, _super);
  71891. /**
  71892. * Creates a new WebVRController from a gamepad
  71893. * @param vrGamepad the gamepad that the WebVRController should be created from
  71894. */
  71895. function WebVRController(vrGamepad) {
  71896. var _this = _super.call(this, vrGamepad) || this;
  71897. // Observables
  71898. /**
  71899. * Fired when the trigger state has changed
  71900. */
  71901. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71902. /**
  71903. * Fired when the main button state has changed
  71904. */
  71905. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71906. /**
  71907. * Fired when the secondary button state has changed
  71908. */
  71909. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71910. /**
  71911. * Fired when the pad state has changed
  71912. */
  71913. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71914. /**
  71915. * Fired when controllers stick values have changed
  71916. */
  71917. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71918. /**
  71919. * X and Y axis corrisponding to the controllers joystick
  71920. */
  71921. _this.pad = { x: 0, y: 0 };
  71922. // avoid GC, store state in a tmp object
  71923. _this._changes = {
  71924. pressChanged: false,
  71925. touchChanged: false,
  71926. valueChanged: false,
  71927. changed: false
  71928. };
  71929. _this._buttons = new Array(vrGamepad.buttons.length);
  71930. _this.hand = vrGamepad.hand;
  71931. return _this;
  71932. }
  71933. /**
  71934. * Fired when a controller button's state has changed
  71935. * @param callback the callback containing the button that was modified
  71936. */
  71937. WebVRController.prototype.onButtonStateChange = function (callback) {
  71938. this._onButtonStateChange = callback;
  71939. };
  71940. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71941. /**
  71942. * The default controller model for the controller
  71943. */
  71944. get: function () {
  71945. return this._defaultModel;
  71946. },
  71947. enumerable: true,
  71948. configurable: true
  71949. });
  71950. /**
  71951. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71952. */
  71953. WebVRController.prototype.update = function () {
  71954. _super.prototype.update.call(this);
  71955. for (var index = 0; index < this._buttons.length; index++) {
  71956. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71957. }
  71958. ;
  71959. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71960. this.pad.x = this.leftStick.x;
  71961. this.pad.y = this.leftStick.y;
  71962. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71963. }
  71964. };
  71965. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71966. if (!newState) {
  71967. newState = {
  71968. pressed: false,
  71969. touched: false,
  71970. value: 0
  71971. };
  71972. }
  71973. if (!currentState) {
  71974. this._buttons[buttonIndex] = {
  71975. pressed: newState.pressed,
  71976. touched: newState.touched,
  71977. value: newState.value
  71978. };
  71979. return;
  71980. }
  71981. this._checkChanges(newState, currentState);
  71982. if (this._changes.changed) {
  71983. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71984. this._handleButtonChange(buttonIndex, newState, this._changes);
  71985. }
  71986. this._buttons[buttonIndex].pressed = newState.pressed;
  71987. this._buttons[buttonIndex].touched = newState.touched;
  71988. // oculus triggers are never 0, thou not touched.
  71989. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71990. };
  71991. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71992. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71993. this._changes.touchChanged = newState.touched !== currentState.touched;
  71994. this._changes.valueChanged = newState.value !== currentState.value;
  71995. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71996. return this._changes;
  71997. };
  71998. /**
  71999. * Disposes of th webVRCOntroller
  72000. */
  72001. WebVRController.prototype.dispose = function () {
  72002. _super.prototype.dispose.call(this);
  72003. this.onTriggerStateChangedObservable.clear();
  72004. this.onMainButtonStateChangedObservable.clear();
  72005. this.onSecondaryButtonStateChangedObservable.clear();
  72006. this.onPadStateChangedObservable.clear();
  72007. this.onPadValuesChangedObservable.clear();
  72008. };
  72009. return WebVRController;
  72010. }(BABYLON.PoseEnabledController));
  72011. BABYLON.WebVRController = WebVRController;
  72012. })(BABYLON || (BABYLON = {}));
  72013. //# sourceMappingURL=babylon.webVRController.js.map
  72014. var BABYLON;
  72015. (function (BABYLON) {
  72016. /**
  72017. * Oculus Touch Controller
  72018. */
  72019. var OculusTouchController = /** @class */ (function (_super) {
  72020. __extends(OculusTouchController, _super);
  72021. /**
  72022. * Creates a new OculusTouchController from a gamepad
  72023. * @param vrGamepad the gamepad that the controller should be created from
  72024. */
  72025. function OculusTouchController(vrGamepad) {
  72026. var _this = _super.call(this, vrGamepad) || this;
  72027. /**
  72028. * Fired when the secondary trigger on this controller is modified
  72029. */
  72030. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72031. /**
  72032. * Fired when the thumb rest on this controller is modified
  72033. */
  72034. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72035. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72036. return _this;
  72037. }
  72038. /**
  72039. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72040. * @param scene scene in which to add meshes
  72041. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72042. */
  72043. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72044. var _this = this;
  72045. var meshName;
  72046. // Hand
  72047. if (this.hand === 'left') {
  72048. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72049. }
  72050. else { // Right is the default if no hand is specified
  72051. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72052. }
  72053. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72054. /*
  72055. Parent Mesh name: oculus_touch_left
  72056. - body
  72057. - trigger
  72058. - thumbstick
  72059. - grip
  72060. - button_y
  72061. - button_x
  72062. - button_enter
  72063. */
  72064. _this._defaultModel = newMeshes[1];
  72065. _this.attachToMesh(_this._defaultModel);
  72066. if (meshLoaded) {
  72067. meshLoaded(_this._defaultModel);
  72068. }
  72069. });
  72070. };
  72071. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72072. /**
  72073. * Fired when the A button on this controller is modified
  72074. */
  72075. get: function () {
  72076. if (this.hand === 'right') {
  72077. return this.onMainButtonStateChangedObservable;
  72078. }
  72079. else {
  72080. throw new Error('No A button on left hand');
  72081. }
  72082. },
  72083. enumerable: true,
  72084. configurable: true
  72085. });
  72086. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72087. /**
  72088. * Fired when the B button on this controller is modified
  72089. */
  72090. get: function () {
  72091. if (this.hand === 'right') {
  72092. return this.onSecondaryButtonStateChangedObservable;
  72093. }
  72094. else {
  72095. throw new Error('No B button on left hand');
  72096. }
  72097. },
  72098. enumerable: true,
  72099. configurable: true
  72100. });
  72101. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72102. /**
  72103. * Fired when the X button on this controller is modified
  72104. */
  72105. get: function () {
  72106. if (this.hand === 'left') {
  72107. return this.onMainButtonStateChangedObservable;
  72108. }
  72109. else {
  72110. throw new Error('No X button on right hand');
  72111. }
  72112. },
  72113. enumerable: true,
  72114. configurable: true
  72115. });
  72116. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72117. /**
  72118. * Fired when the Y button on this controller is modified
  72119. */
  72120. get: function () {
  72121. if (this.hand === 'left') {
  72122. return this.onSecondaryButtonStateChangedObservable;
  72123. }
  72124. else {
  72125. throw new Error('No Y button on right hand');
  72126. }
  72127. },
  72128. enumerable: true,
  72129. configurable: true
  72130. });
  72131. /**
  72132. * Called once for each button that changed state since the last frame
  72133. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72134. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72135. * 2) secondary trigger (same)
  72136. * 3) A (right) X (left), touch, pressed = value
  72137. * 4) B / Y
  72138. * 5) thumb rest
  72139. * @param buttonIdx Which button index changed
  72140. * @param state New state of the button
  72141. * @param changes Which properties on the state changed since last frame
  72142. */
  72143. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72144. var notifyObject = state; //{ state: state, changes: changes };
  72145. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72146. switch (buttonIdx) {
  72147. case 0:
  72148. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72149. return;
  72150. case 1: // index trigger
  72151. if (this._defaultModel) {
  72152. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72153. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72154. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72155. }
  72156. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72157. return;
  72158. case 2: // secondary trigger
  72159. if (this._defaultModel) {
  72160. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72161. }
  72162. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72163. return;
  72164. case 3:
  72165. if (this._defaultModel) {
  72166. if (notifyObject.pressed) {
  72167. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72168. }
  72169. else {
  72170. (this._defaultModel.getChildren()[1]).position.y = 0;
  72171. }
  72172. }
  72173. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72174. return;
  72175. case 4:
  72176. if (this._defaultModel) {
  72177. if (notifyObject.pressed) {
  72178. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72179. }
  72180. else {
  72181. (this._defaultModel.getChildren()[2]).position.y = 0;
  72182. }
  72183. }
  72184. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72185. return;
  72186. case 5:
  72187. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72188. return;
  72189. }
  72190. };
  72191. /**
  72192. * Base Url for the controller model.
  72193. */
  72194. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72195. /**
  72196. * File name for the left controller model.
  72197. */
  72198. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72199. /**
  72200. * File name for the right controller model.
  72201. */
  72202. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72203. return OculusTouchController;
  72204. }(BABYLON.WebVRController));
  72205. BABYLON.OculusTouchController = OculusTouchController;
  72206. })(BABYLON || (BABYLON = {}));
  72207. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72208. var BABYLON;
  72209. (function (BABYLON) {
  72210. /**
  72211. * Vive Controller
  72212. */
  72213. var ViveController = /** @class */ (function (_super) {
  72214. __extends(ViveController, _super);
  72215. /**
  72216. * Creates a new ViveController from a gamepad
  72217. * @param vrGamepad the gamepad that the controller should be created from
  72218. */
  72219. function ViveController(vrGamepad) {
  72220. var _this = _super.call(this, vrGamepad) || this;
  72221. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72222. _this._invertLeftStickY = true;
  72223. return _this;
  72224. }
  72225. /**
  72226. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72227. * @param scene scene in which to add meshes
  72228. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72229. */
  72230. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72231. var _this = this;
  72232. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72233. /*
  72234. Parent Mesh name: ViveWand
  72235. - body
  72236. - r_gripper
  72237. - l_gripper
  72238. - menu_button
  72239. - system_button
  72240. - trackpad
  72241. - trigger
  72242. - LED
  72243. */
  72244. _this._defaultModel = newMeshes[1];
  72245. _this.attachToMesh(_this._defaultModel);
  72246. if (meshLoaded) {
  72247. meshLoaded(_this._defaultModel);
  72248. }
  72249. });
  72250. };
  72251. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72252. /**
  72253. * Fired when the left button on this controller is modified
  72254. */
  72255. get: function () {
  72256. return this.onMainButtonStateChangedObservable;
  72257. },
  72258. enumerable: true,
  72259. configurable: true
  72260. });
  72261. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72262. /**
  72263. * Fired when the right button on this controller is modified
  72264. */
  72265. get: function () {
  72266. return this.onMainButtonStateChangedObservable;
  72267. },
  72268. enumerable: true,
  72269. configurable: true
  72270. });
  72271. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72272. /**
  72273. * Fired when the menu button on this controller is modified
  72274. */
  72275. get: function () {
  72276. return this.onSecondaryButtonStateChangedObservable;
  72277. },
  72278. enumerable: true,
  72279. configurable: true
  72280. });
  72281. /**
  72282. * Called once for each button that changed state since the last frame
  72283. * Vive mapping:
  72284. * 0: touchpad
  72285. * 1: trigger
  72286. * 2: left AND right buttons
  72287. * 3: menu button
  72288. * @param buttonIdx Which button index changed
  72289. * @param state New state of the button
  72290. * @param changes Which properties on the state changed since last frame
  72291. */
  72292. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72293. var notifyObject = state; //{ state: state, changes: changes };
  72294. switch (buttonIdx) {
  72295. case 0:
  72296. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72297. return;
  72298. case 1: // index trigger
  72299. if (this._defaultModel) {
  72300. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72301. }
  72302. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72303. return;
  72304. case 2: // left AND right button
  72305. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72306. return;
  72307. case 3:
  72308. if (this._defaultModel) {
  72309. if (notifyObject.pressed) {
  72310. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72311. }
  72312. else {
  72313. (this._defaultModel.getChildren()[2]).position.y = 0;
  72314. }
  72315. }
  72316. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72317. return;
  72318. }
  72319. };
  72320. /**
  72321. * Base Url for the controller model.
  72322. */
  72323. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72324. /**
  72325. * File name for the controller model.
  72326. */
  72327. ViveController.MODEL_FILENAME = 'wand.babylon';
  72328. return ViveController;
  72329. }(BABYLON.WebVRController));
  72330. BABYLON.ViveController = ViveController;
  72331. })(BABYLON || (BABYLON = {}));
  72332. //# sourceMappingURL=babylon.viveController.js.map
  72333. var BABYLON;
  72334. (function (BABYLON) {
  72335. /**
  72336. * Generic Controller
  72337. */
  72338. var GenericController = /** @class */ (function (_super) {
  72339. __extends(GenericController, _super);
  72340. /**
  72341. * Creates a new GenericController from a gamepad
  72342. * @param vrGamepad the gamepad that the controller should be created from
  72343. */
  72344. function GenericController(vrGamepad) {
  72345. return _super.call(this, vrGamepad) || this;
  72346. }
  72347. /**
  72348. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72349. * @param scene scene in which to add meshes
  72350. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72351. */
  72352. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72353. var _this = this;
  72354. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72355. _this._defaultModel = newMeshes[1];
  72356. _this.attachToMesh(_this._defaultModel);
  72357. if (meshLoaded) {
  72358. meshLoaded(_this._defaultModel);
  72359. }
  72360. });
  72361. };
  72362. /**
  72363. * Called once for each button that changed state since the last frame
  72364. * @param buttonIdx Which button index changed
  72365. * @param state New state of the button
  72366. * @param changes Which properties on the state changed since last frame
  72367. */
  72368. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72369. console.log("Button id: " + buttonIdx + "state: ");
  72370. console.dir(state);
  72371. };
  72372. /**
  72373. * Base Url for the controller model.
  72374. */
  72375. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72376. /**
  72377. * File name for the controller model.
  72378. */
  72379. GenericController.MODEL_FILENAME = 'generic.babylon';
  72380. return GenericController;
  72381. }(BABYLON.WebVRController));
  72382. BABYLON.GenericController = GenericController;
  72383. })(BABYLON || (BABYLON = {}));
  72384. //# sourceMappingURL=babylon.genericController.js.map
  72385. var BABYLON;
  72386. (function (BABYLON) {
  72387. /**
  72388. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72389. */
  72390. var LoadedMeshInfo = /** @class */ (function () {
  72391. function LoadedMeshInfo() {
  72392. /**
  72393. * Map of the button meshes contained in the controller
  72394. */
  72395. this.buttonMeshes = {};
  72396. /**
  72397. * Map of the axis meshes contained in the controller
  72398. */
  72399. this.axisMeshes = {};
  72400. }
  72401. return LoadedMeshInfo;
  72402. }());
  72403. /**
  72404. * Defines the WindowsMotionController object that the state of the windows motion controller
  72405. */
  72406. var WindowsMotionController = /** @class */ (function (_super) {
  72407. __extends(WindowsMotionController, _super);
  72408. /**
  72409. * Creates a new WindowsMotionController from a gamepad
  72410. * @param vrGamepad the gamepad that the controller should be created from
  72411. */
  72412. function WindowsMotionController(vrGamepad) {
  72413. var _this = _super.call(this, vrGamepad) || this;
  72414. _this._mapping = {
  72415. // Semantic button names
  72416. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72417. // A mapping of the button name to glTF model node name
  72418. // that should be transformed by button value.
  72419. buttonMeshNames: {
  72420. 'trigger': 'SELECT',
  72421. 'menu': 'MENU',
  72422. 'grip': 'GRASP',
  72423. 'thumbstick': 'THUMBSTICK_PRESS',
  72424. 'trackpad': 'TOUCHPAD_PRESS'
  72425. },
  72426. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72427. buttonObservableNames: {
  72428. 'trigger': 'onTriggerStateChangedObservable',
  72429. 'menu': 'onSecondaryButtonStateChangedObservable',
  72430. 'grip': 'onMainButtonStateChangedObservable',
  72431. 'thumbstick': 'onPadStateChangedObservable',
  72432. 'trackpad': 'onTrackpadChangedObservable'
  72433. },
  72434. // A mapping of the axis name to glTF model node name
  72435. // that should be transformed by axis value.
  72436. // This array mirrors the browserGamepad.axes array, such that
  72437. // the mesh corresponding to axis 0 is in this array index 0.
  72438. axisMeshNames: [
  72439. 'THUMBSTICK_X',
  72440. 'THUMBSTICK_Y',
  72441. 'TOUCHPAD_TOUCH_X',
  72442. 'TOUCHPAD_TOUCH_Y'
  72443. ],
  72444. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72445. };
  72446. /**
  72447. * Fired when the trackpad on this controller is clicked
  72448. */
  72449. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72450. /**
  72451. * Fired when the trackpad on this controller is modified
  72452. */
  72453. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72454. /**
  72455. * The current x and y values of this controller's trackpad
  72456. */
  72457. _this.trackpad = { x: 0, y: 0 };
  72458. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72459. _this._loadedMeshInfo = null;
  72460. return _this;
  72461. }
  72462. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72463. /**
  72464. * Fired when the trigger on this controller is modified
  72465. */
  72466. get: function () {
  72467. return this.onTriggerStateChangedObservable;
  72468. },
  72469. enumerable: true,
  72470. configurable: true
  72471. });
  72472. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72473. /**
  72474. * Fired when the menu button on this controller is modified
  72475. */
  72476. get: function () {
  72477. return this.onSecondaryButtonStateChangedObservable;
  72478. },
  72479. enumerable: true,
  72480. configurable: true
  72481. });
  72482. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72483. /**
  72484. * Fired when the grip button on this controller is modified
  72485. */
  72486. get: function () {
  72487. return this.onMainButtonStateChangedObservable;
  72488. },
  72489. enumerable: true,
  72490. configurable: true
  72491. });
  72492. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72493. /**
  72494. * Fired when the thumbstick button on this controller is modified
  72495. */
  72496. get: function () {
  72497. return this.onPadStateChangedObservable;
  72498. },
  72499. enumerable: true,
  72500. configurable: true
  72501. });
  72502. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72503. /**
  72504. * Fired when the touchpad button on this controller is modified
  72505. */
  72506. get: function () {
  72507. return this.onTrackpadChangedObservable;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72513. /**
  72514. * Fired when the touchpad values on this controller are modified
  72515. */
  72516. get: function () {
  72517. return this.onTrackpadValuesChangedObservable;
  72518. },
  72519. enumerable: true,
  72520. configurable: true
  72521. });
  72522. WindowsMotionController.prototype._updateTrackpad = function () {
  72523. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72524. this.trackpad.x = this.browserGamepad["axes"][2];
  72525. this.trackpad.y = this.browserGamepad["axes"][3];
  72526. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72527. }
  72528. };
  72529. /**
  72530. * Called once per frame by the engine.
  72531. */
  72532. WindowsMotionController.prototype.update = function () {
  72533. _super.prototype.update.call(this);
  72534. if (this.browserGamepad.axes) {
  72535. this._updateTrackpad();
  72536. // Only need to animate axes if there is a loaded mesh
  72537. if (this._loadedMeshInfo) {
  72538. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72539. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72540. }
  72541. }
  72542. }
  72543. };
  72544. /**
  72545. * Called once for each button that changed state since the last frame
  72546. * @param buttonIdx Which button index changed
  72547. * @param state New state of the button
  72548. * @param changes Which properties on the state changed since last frame
  72549. */
  72550. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72551. var buttonName = this._mapping.buttons[buttonIdx];
  72552. if (!buttonName) {
  72553. return;
  72554. }
  72555. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72556. this._updateTrackpad();
  72557. // Only emit events for buttons that we know how to map from index to name
  72558. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72559. if (observable) {
  72560. observable.notifyObservers(state);
  72561. }
  72562. this._lerpButtonTransform(buttonName, state.value);
  72563. };
  72564. /**
  72565. * Moves the buttons on the controller mesh based on their current state
  72566. * @param buttonName the name of the button to move
  72567. * @param buttonValue the value of the button which determines the buttons new position
  72568. */
  72569. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72570. // If there is no loaded mesh, there is nothing to transform.
  72571. if (!this._loadedMeshInfo) {
  72572. return;
  72573. }
  72574. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72575. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72576. return;
  72577. }
  72578. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72579. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72580. };
  72581. /**
  72582. * Moves the axis on the controller mesh based on its current state
  72583. * @param axis the index of the axis
  72584. * @param axisValue the value of the axis which determines the meshes new position
  72585. * @hidden
  72586. */
  72587. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72588. if (!this._loadedMeshInfo) {
  72589. return;
  72590. }
  72591. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72592. if (!meshInfo) {
  72593. return;
  72594. }
  72595. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72596. return;
  72597. }
  72598. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72599. var lerpValue = axisValue * 0.5 + 0.5;
  72600. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72601. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72602. };
  72603. /**
  72604. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72605. * @param scene scene in which to add meshes
  72606. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72607. */
  72608. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72609. var _this = this;
  72610. if (forceDefault === void 0) { forceDefault = false; }
  72611. var path;
  72612. var filename;
  72613. // Checking if GLB loader is present
  72614. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72615. // Determine the device specific folder based on the ID suffix
  72616. var device = 'default';
  72617. if (this.id && !forceDefault) {
  72618. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72619. device = ((match && match[0]) || device);
  72620. }
  72621. // Hand
  72622. if (this.hand === 'left') {
  72623. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72624. }
  72625. else { // Right is the default if no hand is specified
  72626. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72627. }
  72628. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72629. }
  72630. else {
  72631. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72632. path = BABYLON.GenericController.MODEL_BASE_URL;
  72633. filename = BABYLON.GenericController.MODEL_FILENAME;
  72634. }
  72635. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72636. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72637. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72638. if (!_this._loadedMeshInfo) {
  72639. return;
  72640. }
  72641. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72642. _this.attachToMesh(_this._defaultModel);
  72643. if (meshLoaded) {
  72644. meshLoaded(_this._defaultModel);
  72645. }
  72646. }, null, function (scene, message) {
  72647. BABYLON.Tools.Log(message);
  72648. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72649. if (!forceDefault) {
  72650. _this.initControllerMesh(scene, meshLoaded, true);
  72651. }
  72652. });
  72653. };
  72654. /**
  72655. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72656. * can be transformed by button presses and axes values, based on this._mapping.
  72657. *
  72658. * @param scene scene in which the meshes exist
  72659. * @param meshes list of meshes that make up the controller model to process
  72660. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72661. */
  72662. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72663. var loadedMeshInfo = null;
  72664. // Create a new mesh to contain the glTF hierarchy
  72665. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72666. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72667. var childMesh = null;
  72668. for (var i = 0; i < meshes.length; i++) {
  72669. var mesh = meshes[i];
  72670. if (!mesh.parent) {
  72671. // Exclude controller meshes from picking results
  72672. mesh.isPickable = false;
  72673. // Handle root node, attach to the new parentMesh
  72674. childMesh = mesh;
  72675. break;
  72676. }
  72677. }
  72678. if (childMesh) {
  72679. childMesh.setParent(parentMesh);
  72680. // Create our mesh info. Note that this method will always return non-null.
  72681. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72682. }
  72683. else {
  72684. BABYLON.Tools.Warn('Could not find root node in model file.');
  72685. }
  72686. return loadedMeshInfo;
  72687. };
  72688. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72689. var loadedMeshInfo = new LoadedMeshInfo();
  72690. var i;
  72691. loadedMeshInfo.rootNode = rootNode;
  72692. // Reset the caches
  72693. loadedMeshInfo.buttonMeshes = {};
  72694. loadedMeshInfo.axisMeshes = {};
  72695. // Button Meshes
  72696. for (i = 0; i < this._mapping.buttons.length; i++) {
  72697. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72698. if (!buttonMeshName) {
  72699. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72700. continue;
  72701. }
  72702. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72703. if (!buttonMesh) {
  72704. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72705. continue;
  72706. }
  72707. var buttonMeshInfo = {
  72708. index: i,
  72709. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72710. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72711. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72712. };
  72713. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72714. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72715. }
  72716. else {
  72717. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72718. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72719. '(VALUE: ' + !!buttonMeshInfo.value +
  72720. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72721. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72722. ')');
  72723. }
  72724. }
  72725. // Axis Meshes
  72726. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72727. var axisMeshName = this._mapping.axisMeshNames[i];
  72728. if (!axisMeshName) {
  72729. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72730. continue;
  72731. }
  72732. var axisMesh = getChildByName(rootNode, axisMeshName);
  72733. if (!axisMesh) {
  72734. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72735. continue;
  72736. }
  72737. var axisMeshInfo = {
  72738. index: i,
  72739. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72740. min: getImmediateChildByName(axisMesh, 'MIN'),
  72741. max: getImmediateChildByName(axisMesh, 'MAX')
  72742. };
  72743. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72744. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72745. }
  72746. else {
  72747. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72748. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72749. '(VALUE: ' + !!axisMeshInfo.value +
  72750. ', MIN: ' + !!axisMeshInfo.min +
  72751. ', MAX:' + !!axisMeshInfo.max +
  72752. ')');
  72753. }
  72754. }
  72755. // Pointing Ray
  72756. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72757. if (!loadedMeshInfo.pointingPoseNode) {
  72758. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72759. }
  72760. return loadedMeshInfo;
  72761. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72762. function getChildByName(node, name) {
  72763. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72764. }
  72765. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72766. function getImmediateChildByName(node, name) {
  72767. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72768. }
  72769. };
  72770. /**
  72771. * Gets the ray of the controller in the direction the controller is pointing
  72772. * @param length the length the resulting ray should be
  72773. * @returns a ray in the direction the controller is pointing
  72774. */
  72775. WindowsMotionController.prototype.getForwardRay = function (length) {
  72776. if (length === void 0) { length = 100; }
  72777. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72778. return _super.prototype.getForwardRay.call(this, length);
  72779. }
  72780. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72781. var origin = m.getTranslation();
  72782. var forward = new BABYLON.Vector3(0, 0, -1);
  72783. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72784. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72785. return new BABYLON.Ray(origin, direction, length);
  72786. };
  72787. /**
  72788. * Disposes of the controller
  72789. */
  72790. WindowsMotionController.prototype.dispose = function () {
  72791. _super.prototype.dispose.call(this);
  72792. this.onTrackpadChangedObservable.clear();
  72793. };
  72794. /**
  72795. * The base url used to load the left and right controller models
  72796. */
  72797. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72798. /**
  72799. * The name of the left controller model file
  72800. */
  72801. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72802. /**
  72803. * The name of the right controller model file
  72804. */
  72805. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72806. /**
  72807. * The controller name prefix for this controller type
  72808. */
  72809. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72810. /**
  72811. * The controller id pattern for this controller type
  72812. */
  72813. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72814. return WindowsMotionController;
  72815. }(BABYLON.WebVRController));
  72816. BABYLON.WindowsMotionController = WindowsMotionController;
  72817. })(BABYLON || (BABYLON = {}));
  72818. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72819. var BABYLON;
  72820. (function (BABYLON) {
  72821. /**
  72822. * Gear VR Controller
  72823. */
  72824. var GearVRController = /** @class */ (function (_super) {
  72825. __extends(GearVRController, _super);
  72826. /**
  72827. * Creates a new GearVRController from a gamepad
  72828. * @param vrGamepad the gamepad that the controller should be created from
  72829. */
  72830. function GearVRController(vrGamepad) {
  72831. var _this = _super.call(this, vrGamepad) || this;
  72832. _this._buttonIndexToObservableNameMap = [
  72833. 'onTrackpadChangedObservable',
  72834. 'onTriggerStateChangedObservable' // Trigger
  72835. ];
  72836. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72837. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72838. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72839. return _this;
  72840. }
  72841. /**
  72842. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72843. * @param scene scene in which to add meshes
  72844. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72845. */
  72846. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72847. var _this = this;
  72848. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72849. _this._defaultModel = newMeshes[1];
  72850. _this.attachToMesh(_this._defaultModel);
  72851. if (meshLoaded) {
  72852. meshLoaded(_this._defaultModel);
  72853. }
  72854. });
  72855. };
  72856. /**
  72857. * Called once for each button that changed state since the last frame
  72858. * @param buttonIdx Which button index changed
  72859. * @param state New state of the button
  72860. * @param changes Which properties on the state changed since last frame
  72861. */
  72862. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72863. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72864. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72865. // Only emit events for buttons that we know how to map from index to observable
  72866. var observable = this[observableName];
  72867. if (observable) {
  72868. observable.notifyObservers(state);
  72869. }
  72870. }
  72871. };
  72872. /**
  72873. * Base Url for the controller model.
  72874. */
  72875. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72876. /**
  72877. * File name for the controller model.
  72878. */
  72879. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72880. /**
  72881. * Gamepad Id prefix used to identify this controller.
  72882. */
  72883. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72884. return GearVRController;
  72885. }(BABYLON.WebVRController));
  72886. BABYLON.GearVRController = GearVRController;
  72887. })(BABYLON || (BABYLON = {}));
  72888. //# sourceMappingURL=babylon.gearVRController.js.map
  72889. var BABYLON;
  72890. (function (BABYLON) {
  72891. /**
  72892. * Google Daydream controller
  72893. */
  72894. var DaydreamController = /** @class */ (function (_super) {
  72895. __extends(DaydreamController, _super);
  72896. /**
  72897. * Creates a new DaydreamController from a gamepad
  72898. * @param vrGamepad the gamepad that the controller should be created from
  72899. */
  72900. function DaydreamController(vrGamepad) {
  72901. var _this = _super.call(this, vrGamepad) || this;
  72902. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72903. return _this;
  72904. }
  72905. /**
  72906. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72907. * @param scene scene in which to add meshes
  72908. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72909. */
  72910. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72911. var _this = this;
  72912. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72913. _this._defaultModel = newMeshes[1];
  72914. _this.attachToMesh(_this._defaultModel);
  72915. if (meshLoaded) {
  72916. meshLoaded(_this._defaultModel);
  72917. }
  72918. });
  72919. };
  72920. /**
  72921. * Called once for each button that changed state since the last frame
  72922. * @param buttonIdx Which button index changed
  72923. * @param state New state of the button
  72924. * @param changes Which properties on the state changed since last frame
  72925. */
  72926. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72927. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72928. if (buttonIdx === 0) {
  72929. var observable = this.onTriggerStateChangedObservable;
  72930. if (observable) {
  72931. observable.notifyObservers(state);
  72932. }
  72933. }
  72934. else {
  72935. // If the app or home buttons are ever made available
  72936. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72937. }
  72938. };
  72939. /**
  72940. * Base Url for the controller model.
  72941. */
  72942. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72943. /**
  72944. * File name for the controller model.
  72945. */
  72946. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72947. /**
  72948. * Gamepad Id prefix used to identify Daydream Controller.
  72949. */
  72950. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72951. return DaydreamController;
  72952. }(BABYLON.WebVRController));
  72953. BABYLON.DaydreamController = DaydreamController;
  72954. })(BABYLON || (BABYLON = {}));
  72955. //# sourceMappingURL=babylon.daydreamController.js.map
  72956. var BABYLON;
  72957. (function (BABYLON) {
  72958. var FollowCamera = /** @class */ (function (_super) {
  72959. __extends(FollowCamera, _super);
  72960. function FollowCamera(name, position, scene, lockedTarget) {
  72961. if (lockedTarget === void 0) { lockedTarget = null; }
  72962. var _this = _super.call(this, name, position, scene) || this;
  72963. _this.radius = 12;
  72964. _this.rotationOffset = 0;
  72965. _this.heightOffset = 4;
  72966. _this.cameraAcceleration = 0.05;
  72967. _this.maxCameraSpeed = 20;
  72968. _this.lockedTarget = lockedTarget;
  72969. return _this;
  72970. }
  72971. FollowCamera.prototype.getRadians = function (degrees) {
  72972. return degrees * Math.PI / 180;
  72973. };
  72974. FollowCamera.prototype.follow = function (cameraTarget) {
  72975. if (!cameraTarget)
  72976. return;
  72977. var yRotation;
  72978. if (cameraTarget.rotationQuaternion) {
  72979. var rotMatrix = new BABYLON.Matrix();
  72980. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72981. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72982. }
  72983. else {
  72984. yRotation = cameraTarget.rotation.y;
  72985. }
  72986. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72987. var targetPosition = cameraTarget.getAbsolutePosition();
  72988. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72989. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72990. var dx = targetX - this.position.x;
  72991. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72992. var dz = (targetZ) - this.position.z;
  72993. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72994. var vy = dy * this.cameraAcceleration;
  72995. var vz = dz * this.cameraAcceleration * 2;
  72996. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72997. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72998. }
  72999. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73000. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73001. }
  73002. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73003. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73004. }
  73005. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73006. this.setTarget(targetPosition);
  73007. };
  73008. FollowCamera.prototype._checkInputs = function () {
  73009. _super.prototype._checkInputs.call(this);
  73010. if (this.lockedTarget) {
  73011. this.follow(this.lockedTarget);
  73012. }
  73013. };
  73014. FollowCamera.prototype.getClassName = function () {
  73015. return "FollowCamera";
  73016. };
  73017. __decorate([
  73018. BABYLON.serialize()
  73019. ], FollowCamera.prototype, "radius", void 0);
  73020. __decorate([
  73021. BABYLON.serialize()
  73022. ], FollowCamera.prototype, "rotationOffset", void 0);
  73023. __decorate([
  73024. BABYLON.serialize()
  73025. ], FollowCamera.prototype, "heightOffset", void 0);
  73026. __decorate([
  73027. BABYLON.serialize()
  73028. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73029. __decorate([
  73030. BABYLON.serialize()
  73031. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73032. __decorate([
  73033. BABYLON.serializeAsMeshReference("lockedTargetId")
  73034. ], FollowCamera.prototype, "lockedTarget", void 0);
  73035. return FollowCamera;
  73036. }(BABYLON.TargetCamera));
  73037. BABYLON.FollowCamera = FollowCamera;
  73038. var ArcFollowCamera = /** @class */ (function (_super) {
  73039. __extends(ArcFollowCamera, _super);
  73040. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73041. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73042. _this.alpha = alpha;
  73043. _this.beta = beta;
  73044. _this.radius = radius;
  73045. _this.target = target;
  73046. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73047. _this.follow();
  73048. return _this;
  73049. }
  73050. ArcFollowCamera.prototype.follow = function () {
  73051. if (!this.target) {
  73052. return;
  73053. }
  73054. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73055. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73056. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73057. var targetPosition = this.target.getAbsolutePosition();
  73058. this.position = targetPosition.add(this._cartesianCoordinates);
  73059. this.setTarget(targetPosition);
  73060. };
  73061. ArcFollowCamera.prototype._checkInputs = function () {
  73062. _super.prototype._checkInputs.call(this);
  73063. this.follow();
  73064. };
  73065. ArcFollowCamera.prototype.getClassName = function () {
  73066. return "ArcFollowCamera";
  73067. };
  73068. return ArcFollowCamera;
  73069. }(BABYLON.TargetCamera));
  73070. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73071. })(BABYLON || (BABYLON = {}));
  73072. //# sourceMappingURL=babylon.followCamera.js.map
  73073. var BABYLON;
  73074. (function (BABYLON) {
  73075. // We're mainly based on the logic defined into the FreeCamera code
  73076. var UniversalCamera = /** @class */ (function (_super) {
  73077. __extends(UniversalCamera, _super);
  73078. //-- end properties for backward compatibility for inputs
  73079. function UniversalCamera(name, position, scene) {
  73080. var _this = _super.call(this, name, position, scene) || this;
  73081. _this.inputs.addGamepad();
  73082. return _this;
  73083. }
  73084. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73085. //-- Begin properties for backward compatibility for inputs
  73086. get: function () {
  73087. var gamepad = this.inputs.attached["gamepad"];
  73088. if (gamepad)
  73089. return gamepad.gamepadAngularSensibility;
  73090. return 0;
  73091. },
  73092. set: function (value) {
  73093. var gamepad = this.inputs.attached["gamepad"];
  73094. if (gamepad)
  73095. gamepad.gamepadAngularSensibility = value;
  73096. },
  73097. enumerable: true,
  73098. configurable: true
  73099. });
  73100. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73101. get: function () {
  73102. var gamepad = this.inputs.attached["gamepad"];
  73103. if (gamepad)
  73104. return gamepad.gamepadMoveSensibility;
  73105. return 0;
  73106. },
  73107. set: function (value) {
  73108. var gamepad = this.inputs.attached["gamepad"];
  73109. if (gamepad)
  73110. gamepad.gamepadMoveSensibility = value;
  73111. },
  73112. enumerable: true,
  73113. configurable: true
  73114. });
  73115. UniversalCamera.prototype.getClassName = function () {
  73116. return "UniversalCamera";
  73117. };
  73118. return UniversalCamera;
  73119. }(BABYLON.TouchCamera));
  73120. BABYLON.UniversalCamera = UniversalCamera;
  73121. })(BABYLON || (BABYLON = {}));
  73122. //# sourceMappingURL=babylon.universalCamera.js.map
  73123. var BABYLON;
  73124. (function (BABYLON) {
  73125. // We're mainly based on the logic defined into the FreeCamera code
  73126. var GamepadCamera = /** @class */ (function (_super) {
  73127. __extends(GamepadCamera, _super);
  73128. //-- end properties for backward compatibility for inputs
  73129. function GamepadCamera(name, position, scene) {
  73130. return _super.call(this, name, position, scene) || this;
  73131. }
  73132. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73133. //-- Begin properties for backward compatibility for inputs
  73134. get: function () {
  73135. var gamepad = this.inputs.attached["gamepad"];
  73136. if (gamepad)
  73137. return gamepad.gamepadAngularSensibility;
  73138. return 0;
  73139. },
  73140. set: function (value) {
  73141. var gamepad = this.inputs.attached["gamepad"];
  73142. if (gamepad)
  73143. gamepad.gamepadAngularSensibility = value;
  73144. },
  73145. enumerable: true,
  73146. configurable: true
  73147. });
  73148. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73149. get: function () {
  73150. var gamepad = this.inputs.attached["gamepad"];
  73151. if (gamepad)
  73152. return gamepad.gamepadMoveSensibility;
  73153. return 0;
  73154. },
  73155. set: function (value) {
  73156. var gamepad = this.inputs.attached["gamepad"];
  73157. if (gamepad)
  73158. gamepad.gamepadMoveSensibility = value;
  73159. },
  73160. enumerable: true,
  73161. configurable: true
  73162. });
  73163. GamepadCamera.prototype.getClassName = function () {
  73164. return "GamepadCamera";
  73165. };
  73166. return GamepadCamera;
  73167. }(BABYLON.UniversalCamera));
  73168. BABYLON.GamepadCamera = GamepadCamera;
  73169. })(BABYLON || (BABYLON = {}));
  73170. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73171. var BABYLON;
  73172. (function (BABYLON) {
  73173. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73174. function PostProcessRenderPipelineManager() {
  73175. this._renderPipelines = {};
  73176. }
  73177. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73178. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73179. };
  73180. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73181. if (unique === void 0) { unique = false; }
  73182. var renderPipeline = this._renderPipelines[renderPipelineName];
  73183. if (!renderPipeline) {
  73184. return;
  73185. }
  73186. renderPipeline._attachCameras(cameras, unique);
  73187. };
  73188. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73189. var renderPipeline = this._renderPipelines[renderPipelineName];
  73190. if (!renderPipeline) {
  73191. return;
  73192. }
  73193. renderPipeline._detachCameras(cameras);
  73194. };
  73195. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73196. var renderPipeline = this._renderPipelines[renderPipelineName];
  73197. if (!renderPipeline) {
  73198. return;
  73199. }
  73200. renderPipeline._enableEffect(renderEffectName, cameras);
  73201. };
  73202. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73203. var renderPipeline = this._renderPipelines[renderPipelineName];
  73204. if (!renderPipeline) {
  73205. return;
  73206. }
  73207. renderPipeline._disableEffect(renderEffectName, cameras);
  73208. };
  73209. PostProcessRenderPipelineManager.prototype.update = function () {
  73210. for (var renderPipelineName in this._renderPipelines) {
  73211. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73212. var pipeline = this._renderPipelines[renderPipelineName];
  73213. if (!pipeline.isSupported) {
  73214. pipeline.dispose();
  73215. delete this._renderPipelines[renderPipelineName];
  73216. }
  73217. else {
  73218. pipeline._update();
  73219. }
  73220. }
  73221. }
  73222. };
  73223. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73224. for (var renderPipelineName in this._renderPipelines) {
  73225. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73226. var pipeline = this._renderPipelines[renderPipelineName];
  73227. pipeline._rebuild();
  73228. }
  73229. }
  73230. };
  73231. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73232. for (var renderPipelineName in this._renderPipelines) {
  73233. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73234. var pipeline = this._renderPipelines[renderPipelineName];
  73235. pipeline.dispose();
  73236. }
  73237. }
  73238. };
  73239. return PostProcessRenderPipelineManager;
  73240. }());
  73241. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73242. })(BABYLON || (BABYLON = {}));
  73243. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73244. var BABYLON;
  73245. (function (BABYLON) {
  73246. /**
  73247. * This represents a set of one or more post processes in Babylon.
  73248. * A post process can be used to apply a shader to a texture after it is rendered.
  73249. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73250. */
  73251. var PostProcessRenderEffect = /** @class */ (function () {
  73252. /**
  73253. * Instantiates a post process render effect.
  73254. * A post process can be used to apply a shader to a texture after it is rendered.
  73255. * @param engine The engine the effect is tied to
  73256. * @param name The name of the effect
  73257. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73258. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73259. */
  73260. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73261. this._name = name;
  73262. this._singleInstance = singleInstance || true;
  73263. this._getPostProcesses = getPostProcesses;
  73264. this._cameras = {};
  73265. this._indicesForCamera = {};
  73266. this._postProcesses = {};
  73267. }
  73268. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73269. /**
  73270. * Checks if all the post processes in the effect are supported.
  73271. */
  73272. get: function () {
  73273. for (var index in this._postProcesses) {
  73274. if (this._postProcesses.hasOwnProperty(index)) {
  73275. var pps = this._postProcesses[index];
  73276. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73277. if (!pps[ppIndex].isSupported) {
  73278. return false;
  73279. }
  73280. }
  73281. }
  73282. }
  73283. return true;
  73284. },
  73285. enumerable: true,
  73286. configurable: true
  73287. });
  73288. /**
  73289. * Updates the current state of the effect
  73290. */
  73291. PostProcessRenderEffect.prototype._update = function () {
  73292. };
  73293. /**
  73294. * Attaches the effect on cameras
  73295. * @param cameras The camera to attach to.
  73296. */
  73297. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73298. var _this = this;
  73299. var cameraKey;
  73300. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73301. if (!cams) {
  73302. return;
  73303. }
  73304. for (var i = 0; i < cams.length; i++) {
  73305. var camera = cams[i];
  73306. var cameraName = camera.name;
  73307. if (this._singleInstance) {
  73308. cameraKey = 0;
  73309. }
  73310. else {
  73311. cameraKey = cameraName;
  73312. }
  73313. if (!this._postProcesses[cameraKey]) {
  73314. var postProcess = this._getPostProcesses();
  73315. if (postProcess) {
  73316. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73317. }
  73318. }
  73319. if (!this._indicesForCamera[cameraName]) {
  73320. this._indicesForCamera[cameraName] = [];
  73321. }
  73322. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73323. var index = camera.attachPostProcess(postProcess);
  73324. _this._indicesForCamera[cameraName].push(index);
  73325. });
  73326. if (!this._cameras[cameraName]) {
  73327. this._cameras[cameraName] = camera;
  73328. }
  73329. }
  73330. };
  73331. /**
  73332. * Detatches the effect on cameras
  73333. * @param cameras The camera to detatch from.
  73334. */
  73335. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73336. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73337. if (!cams) {
  73338. return;
  73339. }
  73340. for (var i = 0; i < cams.length; i++) {
  73341. var camera = cams[i];
  73342. var cameraName = camera.name;
  73343. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73344. camera.detachPostProcess(postProcess);
  73345. });
  73346. if (this._cameras[cameraName]) {
  73347. //this._indicesForCamera.splice(index, 1);
  73348. this._cameras[cameraName] = null;
  73349. }
  73350. }
  73351. };
  73352. /**
  73353. * Enables the effect on given cameras
  73354. * @param cameras The camera to enable.
  73355. */
  73356. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73357. var _this = this;
  73358. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73359. if (!cams) {
  73360. return;
  73361. }
  73362. for (var i = 0; i < cams.length; i++) {
  73363. var camera = cams[i];
  73364. var cameraName = camera.name;
  73365. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73366. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73367. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73368. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73369. });
  73370. }
  73371. }
  73372. }
  73373. };
  73374. /**
  73375. * Disables the effect on the given cameras
  73376. * @param cameras The camera to disable.
  73377. */
  73378. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73379. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73380. if (!cams) {
  73381. return;
  73382. }
  73383. for (var i = 0; i < cams.length; i++) {
  73384. var camera = cams[i];
  73385. var cameraName = camera.name;
  73386. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73387. camera.detachPostProcess(postProcess);
  73388. });
  73389. }
  73390. };
  73391. /**
  73392. * Gets a list of the post processes contained in the effect.
  73393. * @param camera The camera to get the post processes on.
  73394. * @returns The list of the post processes in the effect.
  73395. */
  73396. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73397. if (this._singleInstance) {
  73398. return this._postProcesses[0];
  73399. }
  73400. else {
  73401. if (!camera) {
  73402. return null;
  73403. }
  73404. return this._postProcesses[camera.name];
  73405. }
  73406. };
  73407. return PostProcessRenderEffect;
  73408. }());
  73409. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73410. })(BABYLON || (BABYLON = {}));
  73411. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73412. var BABYLON;
  73413. (function (BABYLON) {
  73414. var PostProcessRenderPipeline = /** @class */ (function () {
  73415. function PostProcessRenderPipeline(engine, name) {
  73416. this.engine = engine;
  73417. this._name = name;
  73418. this._renderEffects = {};
  73419. this._renderEffectsForIsolatedPass = new Array();
  73420. this._cameras = [];
  73421. }
  73422. PostProcessRenderPipeline.prototype.getClassName = function () {
  73423. return "PostProcessRenderPipeline";
  73424. };
  73425. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73426. get: function () {
  73427. for (var renderEffectName in this._renderEffects) {
  73428. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73429. if (!this._renderEffects[renderEffectName].isSupported) {
  73430. return false;
  73431. }
  73432. }
  73433. }
  73434. return true;
  73435. },
  73436. enumerable: true,
  73437. configurable: true
  73438. });
  73439. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73440. this._renderEffects[renderEffect._name] = renderEffect;
  73441. };
  73442. // private
  73443. PostProcessRenderPipeline.prototype._rebuild = function () {
  73444. };
  73445. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73446. var renderEffects = this._renderEffects[renderEffectName];
  73447. if (!renderEffects) {
  73448. return;
  73449. }
  73450. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73451. };
  73452. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73453. var renderEffects = this._renderEffects[renderEffectName];
  73454. if (!renderEffects) {
  73455. return;
  73456. }
  73457. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73458. };
  73459. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73460. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73461. if (!cams) {
  73462. return;
  73463. }
  73464. var indicesToDelete = [];
  73465. var i;
  73466. for (i = 0; i < cams.length; i++) {
  73467. var camera = cams[i];
  73468. var cameraName = camera.name;
  73469. if (this._cameras.indexOf(camera) === -1) {
  73470. this._cameras[cameraName] = camera;
  73471. }
  73472. else if (unique) {
  73473. indicesToDelete.push(i);
  73474. }
  73475. }
  73476. for (i = 0; i < indicesToDelete.length; i++) {
  73477. cameras.splice(indicesToDelete[i], 1);
  73478. }
  73479. for (var renderEffectName in this._renderEffects) {
  73480. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73481. this._renderEffects[renderEffectName]._attachCameras(cams);
  73482. }
  73483. }
  73484. };
  73485. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73486. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73487. if (!cams) {
  73488. return;
  73489. }
  73490. for (var renderEffectName in this._renderEffects) {
  73491. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73492. this._renderEffects[renderEffectName]._detachCameras(cams);
  73493. }
  73494. }
  73495. for (var i = 0; i < cams.length; i++) {
  73496. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73497. }
  73498. };
  73499. PostProcessRenderPipeline.prototype._update = function () {
  73500. for (var renderEffectName in this._renderEffects) {
  73501. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73502. this._renderEffects[renderEffectName]._update();
  73503. }
  73504. }
  73505. for (var i = 0; i < this._cameras.length; i++) {
  73506. var cameraName = this._cameras[i].name;
  73507. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73508. this._renderEffectsForIsolatedPass[cameraName]._update();
  73509. }
  73510. }
  73511. };
  73512. PostProcessRenderPipeline.prototype._reset = function () {
  73513. this._renderEffects = {};
  73514. this._renderEffectsForIsolatedPass = new Array();
  73515. };
  73516. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73517. // 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)
  73518. var effectKeys = Object.keys(this._renderEffects);
  73519. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73520. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73521. if (postProcesses) {
  73522. postProcesses[0].samples = sampleCount;
  73523. return true;
  73524. }
  73525. }
  73526. return false;
  73527. };
  73528. PostProcessRenderPipeline.prototype.dispose = function () {
  73529. // Must be implemented by children
  73530. };
  73531. __decorate([
  73532. BABYLON.serialize()
  73533. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73534. return PostProcessRenderPipeline;
  73535. }());
  73536. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73537. })(BABYLON || (BABYLON = {}));
  73538. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73539. var BABYLON;
  73540. (function (BABYLON) {
  73541. /**
  73542. * This represents a depth renderer in Babylon.
  73543. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73544. */
  73545. var DepthRenderer = /** @class */ (function () {
  73546. /**
  73547. * Instantiates a depth renderer
  73548. * @param scene The scene the renderer belongs to
  73549. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73550. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73551. */
  73552. function DepthRenderer(scene, type, camera) {
  73553. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73554. if (camera === void 0) { camera = null; }
  73555. var _this = this;
  73556. this._scene = scene;
  73557. this._camera = camera;
  73558. var engine = scene.getEngine();
  73559. // Render target
  73560. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73561. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73562. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73563. this._depthMap.refreshRate = 1;
  73564. this._depthMap.renderParticles = false;
  73565. this._depthMap.renderList = null;
  73566. // Camera to get depth map from to support multiple concurrent cameras
  73567. this._depthMap.activeCamera = this._camera;
  73568. this._depthMap.ignoreCameraViewport = true;
  73569. this._depthMap.useCameraPostProcesses = false;
  73570. // set default depth value to 1.0 (far away)
  73571. this._depthMap.onClearObservable.add(function (engine) {
  73572. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73573. });
  73574. // Custom render function
  73575. var renderSubMesh = function (subMesh) {
  73576. var mesh = subMesh.getRenderingMesh();
  73577. var scene = _this._scene;
  73578. var engine = scene.getEngine();
  73579. var material = subMesh.getMaterial();
  73580. if (!material) {
  73581. return;
  73582. }
  73583. // Culling and reverse (right handed system)
  73584. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73585. // Managing instances
  73586. var batch = mesh._getInstancesRenderList(subMesh._id);
  73587. if (batch.mustReturn) {
  73588. return;
  73589. }
  73590. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73591. var camera = _this._camera || scene.activeCamera;
  73592. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73593. engine.enableEffect(_this._effect);
  73594. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73595. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73596. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73597. // Alpha test
  73598. if (material && material.needAlphaTesting()) {
  73599. var alphaTexture = material.getAlphaTestTexture();
  73600. if (alphaTexture) {
  73601. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73602. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73603. }
  73604. }
  73605. // Bones
  73606. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73607. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73608. }
  73609. // Draw
  73610. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73611. }
  73612. };
  73613. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73614. var index;
  73615. if (depthOnlySubMeshes.length) {
  73616. engine.setColorWrite(false);
  73617. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73618. renderSubMesh(depthOnlySubMeshes.data[index]);
  73619. }
  73620. engine.setColorWrite(true);
  73621. }
  73622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73623. renderSubMesh(opaqueSubMeshes.data[index]);
  73624. }
  73625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73626. renderSubMesh(alphaTestSubMeshes.data[index]);
  73627. }
  73628. };
  73629. }
  73630. /**
  73631. * Creates the depth rendering effect and checks if the effect is ready.
  73632. * @param subMesh The submesh to be used to render the depth map of
  73633. * @param useInstances If multiple world instances should be used
  73634. * @returns if the depth renderer is ready to render the depth map
  73635. */
  73636. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73637. var material = subMesh.getMaterial();
  73638. if (material.disableDepthWrite) {
  73639. return false;
  73640. }
  73641. var defines = [];
  73642. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73643. var mesh = subMesh.getMesh();
  73644. // Alpha test
  73645. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73646. defines.push("#define ALPHATEST");
  73647. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73648. attribs.push(BABYLON.VertexBuffer.UVKind);
  73649. defines.push("#define UV1");
  73650. }
  73651. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73652. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73653. defines.push("#define UV2");
  73654. }
  73655. }
  73656. // Bones
  73657. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73658. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73659. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73660. if (mesh.numBoneInfluencers > 4) {
  73661. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73662. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73663. }
  73664. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73665. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73666. }
  73667. else {
  73668. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73669. }
  73670. // Instances
  73671. if (useInstances) {
  73672. defines.push("#define INSTANCES");
  73673. attribs.push("world0");
  73674. attribs.push("world1");
  73675. attribs.push("world2");
  73676. attribs.push("world3");
  73677. }
  73678. // Get correct effect
  73679. var join = defines.join("\n");
  73680. if (this._cachedDefines !== join) {
  73681. this._cachedDefines = join;
  73682. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73683. }
  73684. return this._effect.isReady();
  73685. };
  73686. /**
  73687. * Gets the texture which the depth map will be written to.
  73688. * @returns The depth map texture
  73689. */
  73690. DepthRenderer.prototype.getDepthMap = function () {
  73691. return this._depthMap;
  73692. };
  73693. /**
  73694. * Disposes of the depth renderer.
  73695. */
  73696. DepthRenderer.prototype.dispose = function () {
  73697. this._depthMap.dispose();
  73698. };
  73699. return DepthRenderer;
  73700. }());
  73701. BABYLON.DepthRenderer = DepthRenderer;
  73702. })(BABYLON || (BABYLON = {}));
  73703. //# sourceMappingURL=babylon.depthRenderer.js.map
  73704. var BABYLON;
  73705. (function (BABYLON) {
  73706. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73707. __extends(SSAORenderingPipeline, _super);
  73708. /**
  73709. * @constructor
  73710. * @param {string} name - The rendering pipeline name
  73711. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73712. * @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 }
  73713. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73714. */
  73715. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73716. var _this = _super.call(this, scene.getEngine(), name) || this;
  73717. // Members
  73718. /**
  73719. * The PassPostProcess id in the pipeline that contains the original scene color
  73720. */
  73721. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73722. /**
  73723. * The SSAO PostProcess id in the pipeline
  73724. */
  73725. _this.SSAORenderEffect = "SSAORenderEffect";
  73726. /**
  73727. * The horizontal blur PostProcess id in the pipeline
  73728. */
  73729. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73730. /**
  73731. * The vertical blur PostProcess id in the pipeline
  73732. */
  73733. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73734. /**
  73735. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73736. */
  73737. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73738. /**
  73739. * The output strength of the SSAO post-process. Default value is 1.0.
  73740. */
  73741. _this.totalStrength = 1.0;
  73742. /**
  73743. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73744. */
  73745. _this.radius = 0.0001;
  73746. /**
  73747. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73748. * Must not be equal to fallOff and superior to fallOff.
  73749. * Default value is 0.975
  73750. */
  73751. _this.area = 0.0075;
  73752. /**
  73753. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73754. * Must not be equal to area and inferior to area.
  73755. * Default value is 0.0
  73756. */
  73757. _this.fallOff = 0.000001;
  73758. /**
  73759. * The base color of the SSAO post-process
  73760. * The final result is "base + ssao" between [0, 1]
  73761. */
  73762. _this.base = 0.5;
  73763. _this._firstUpdate = true;
  73764. _this._scene = scene;
  73765. // Set up assets
  73766. _this._createRandomTexture();
  73767. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73768. var ssaoRatio = ratio.ssaoRatio || ratio;
  73769. var combineRatio = ratio.combineRatio || ratio;
  73770. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73771. _this._createSSAOPostProcess(ssaoRatio);
  73772. _this._createBlurPostProcess(ssaoRatio);
  73773. _this._createSSAOCombinePostProcess(combineRatio);
  73774. // Set up pipeline
  73775. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73776. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73777. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73778. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73779. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73780. // Finish
  73781. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73782. if (cameras)
  73783. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73784. return _this;
  73785. }
  73786. // Public Methods
  73787. /**
  73788. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73789. */
  73790. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73791. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73792. for (var i = 0; i < this._scene.cameras.length; i++) {
  73793. var camera = this._scene.cameras[i];
  73794. this._originalColorPostProcess.dispose(camera);
  73795. this._ssaoPostProcess.dispose(camera);
  73796. this._blurHPostProcess.dispose(camera);
  73797. this._blurVPostProcess.dispose(camera);
  73798. this._ssaoCombinePostProcess.dispose(camera);
  73799. }
  73800. this._randomTexture.dispose();
  73801. if (disableDepthRender)
  73802. this._scene.disableDepthRenderer();
  73803. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73804. _super.prototype.dispose.call(this);
  73805. };
  73806. // Private Methods
  73807. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73808. var _this = this;
  73809. var size = 16;
  73810. 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);
  73811. 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);
  73812. this._blurHPostProcess.onActivateObservable.add(function () {
  73813. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73814. _this._blurHPostProcess.kernel = size * dw;
  73815. });
  73816. this._blurVPostProcess.onActivateObservable.add(function () {
  73817. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73818. _this._blurVPostProcess.kernel = size * dw;
  73819. });
  73820. };
  73821. SSAORenderingPipeline.prototype._rebuild = function () {
  73822. this._firstUpdate = true;
  73823. _super.prototype._rebuild.call(this);
  73824. };
  73825. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73826. var _this = this;
  73827. var numSamples = 16;
  73828. var sampleSphere = [
  73829. 0.5381, 0.1856, -0.4319,
  73830. 0.1379, 0.2486, 0.4430,
  73831. 0.3371, 0.5679, -0.0057,
  73832. -0.6999, -0.0451, -0.0019,
  73833. 0.0689, -0.1598, -0.8547,
  73834. 0.0560, 0.0069, -0.1843,
  73835. -0.0146, 0.1402, 0.0762,
  73836. 0.0100, -0.1924, -0.0344,
  73837. -0.3577, -0.5301, -0.4358,
  73838. -0.3169, 0.1063, 0.0158,
  73839. 0.0103, -0.5869, 0.0046,
  73840. -0.0897, -0.4940, 0.3287,
  73841. 0.7119, -0.0154, -0.0918,
  73842. -0.0533, 0.0596, -0.5411,
  73843. 0.0352, -0.0631, 0.5460,
  73844. -0.4776, 0.2847, -0.0271
  73845. ];
  73846. var samplesFactor = 1.0 / numSamples;
  73847. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73848. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73849. "area", "fallOff", "base", "range", "viewport"
  73850. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73851. this._ssaoPostProcess.onApply = function (effect) {
  73852. if (_this._firstUpdate) {
  73853. effect.setArray3("sampleSphere", sampleSphere);
  73854. effect.setFloat("samplesFactor", samplesFactor);
  73855. effect.setFloat("randTextureTiles", 4.0);
  73856. }
  73857. effect.setFloat("totalStrength", _this.totalStrength);
  73858. effect.setFloat("radius", _this.radius);
  73859. effect.setFloat("area", _this.area);
  73860. effect.setFloat("fallOff", _this.fallOff);
  73861. effect.setFloat("base", _this.base);
  73862. effect.setTexture("textureSampler", _this._depthTexture);
  73863. effect.setTexture("randomSampler", _this._randomTexture);
  73864. };
  73865. };
  73866. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73867. var _this = this;
  73868. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73869. this._ssaoCombinePostProcess.onApply = function (effect) {
  73870. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73871. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73872. };
  73873. };
  73874. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73875. var size = 512;
  73876. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73877. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73878. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73879. var context = this._randomTexture.getContext();
  73880. var rand = function (min, max) {
  73881. return Math.random() * (max - min) + min;
  73882. };
  73883. var randVector = BABYLON.Vector3.Zero();
  73884. for (var x = 0; x < size; x++) {
  73885. for (var y = 0; y < size; y++) {
  73886. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73887. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73888. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73889. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73890. context.fillRect(x, y, 1, 1);
  73891. }
  73892. }
  73893. this._randomTexture.update(false);
  73894. };
  73895. __decorate([
  73896. BABYLON.serialize()
  73897. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73898. __decorate([
  73899. BABYLON.serialize()
  73900. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73901. __decorate([
  73902. BABYLON.serialize()
  73903. ], SSAORenderingPipeline.prototype, "area", void 0);
  73904. __decorate([
  73905. BABYLON.serialize()
  73906. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73907. __decorate([
  73908. BABYLON.serialize()
  73909. ], SSAORenderingPipeline.prototype, "base", void 0);
  73910. return SSAORenderingPipeline;
  73911. }(BABYLON.PostProcessRenderPipeline));
  73912. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73913. })(BABYLON || (BABYLON = {}));
  73914. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73915. var BABYLON;
  73916. (function (BABYLON) {
  73917. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73918. __extends(SSAO2RenderingPipeline, _super);
  73919. /**
  73920. * @constructor
  73921. * @param {string} name - The rendering pipeline name
  73922. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73923. * @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 }
  73924. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73925. */
  73926. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73927. var _this = _super.call(this, scene.getEngine(), name) || this;
  73928. // Members
  73929. /**
  73930. * The PassPostProcess id in the pipeline that contains the original scene color
  73931. */
  73932. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73933. /**
  73934. * The SSAO PostProcess id in the pipeline
  73935. */
  73936. _this.SSAORenderEffect = "SSAORenderEffect";
  73937. /**
  73938. * The horizontal blur PostProcess id in the pipeline
  73939. */
  73940. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73941. /**
  73942. * The vertical blur PostProcess id in the pipeline
  73943. */
  73944. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73945. /**
  73946. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73947. */
  73948. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73949. /**
  73950. * The output strength of the SSAO post-process. Default value is 1.0.
  73951. */
  73952. _this.totalStrength = 1.0;
  73953. /**
  73954. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73955. */
  73956. _this.maxZ = 100.0;
  73957. /**
  73958. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73959. */
  73960. _this.minZAspect = 0.2;
  73961. /**
  73962. * Number of samples used for the SSAO calculations. Default value is 8
  73963. */
  73964. _this._samples = 8;
  73965. /**
  73966. * Are we using bilateral blur ?
  73967. */
  73968. _this._expensiveBlur = true;
  73969. /**
  73970. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73971. */
  73972. _this.radius = 2.0;
  73973. /**
  73974. * The base color of the SSAO post-process
  73975. * The final result is "base + ssao" between [0, 1]
  73976. */
  73977. _this.base = 0.1;
  73978. _this._firstUpdate = true;
  73979. _this._scene = scene;
  73980. _this._ratio = ratio;
  73981. if (!_this.isSupported) {
  73982. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73983. return _this;
  73984. }
  73985. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73986. var blurRatio = _this._ratio.blurRatio || ratio;
  73987. // Set up assets
  73988. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73989. _this._createRandomTexture();
  73990. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73991. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73992. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73993. _this._createSSAOPostProcess(1.0);
  73994. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73995. _this._createSSAOCombinePostProcess(blurRatio);
  73996. // Set up pipeline
  73997. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73998. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74002. // Finish
  74003. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74004. if (cameras)
  74005. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74006. return _this;
  74007. }
  74008. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74009. get: function () {
  74010. return this._samples;
  74011. },
  74012. set: function (n) {
  74013. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74014. this._samples = n;
  74015. this._sampleSphere = this._generateHemisphere();
  74016. this._firstUpdate = true;
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74022. get: function () {
  74023. return this._expensiveBlur;
  74024. },
  74025. set: function (b) {
  74026. 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"]);
  74027. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74028. this._expensiveBlur = b;
  74029. this._firstUpdate = true;
  74030. },
  74031. enumerable: true,
  74032. configurable: true
  74033. });
  74034. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74035. /**
  74036. * Support test.
  74037. */
  74038. get: function () {
  74039. var engine = BABYLON.Engine.LastCreatedEngine;
  74040. if (!engine) {
  74041. return false;
  74042. }
  74043. return engine.getCaps().drawBuffersExtension;
  74044. },
  74045. enumerable: true,
  74046. configurable: true
  74047. });
  74048. // Public Methods
  74049. /**
  74050. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74051. */
  74052. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74053. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74054. for (var i = 0; i < this._scene.cameras.length; i++) {
  74055. var camera = this._scene.cameras[i];
  74056. this._originalColorPostProcess.dispose(camera);
  74057. this._ssaoPostProcess.dispose(camera);
  74058. this._blurHPostProcess.dispose(camera);
  74059. this._blurVPostProcess.dispose(camera);
  74060. this._ssaoCombinePostProcess.dispose(camera);
  74061. }
  74062. this._randomTexture.dispose();
  74063. if (disableGeometryBufferRenderer)
  74064. this._scene.disableGeometryBufferRenderer();
  74065. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74066. _super.prototype.dispose.call(this);
  74067. };
  74068. // Private Methods
  74069. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74070. var _this = this;
  74071. this._samplerOffsets = [];
  74072. var expensive = this.expensiveBlur;
  74073. for (var i = -8; i < 8; i++) {
  74074. this._samplerOffsets.push(i * 2 + 0.5);
  74075. }
  74076. 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");
  74077. this._blurHPostProcess.onApply = function (effect) {
  74078. if (!_this._scene.activeCamera) {
  74079. return;
  74080. }
  74081. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74082. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74083. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74084. effect.setFloat("radius", _this.radius);
  74085. effect.setTexture("depthSampler", _this._depthTexture);
  74086. if (_this._firstUpdate) {
  74087. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74088. }
  74089. };
  74090. 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");
  74091. this._blurVPostProcess.onApply = function (effect) {
  74092. if (!_this._scene.activeCamera) {
  74093. return;
  74094. }
  74095. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74096. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74097. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74098. effect.setFloat("radius", _this.radius);
  74099. effect.setTexture("depthSampler", _this._depthTexture);
  74100. if (_this._firstUpdate) {
  74101. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74102. _this._firstUpdate = false;
  74103. }
  74104. };
  74105. };
  74106. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74107. this._firstUpdate = true;
  74108. _super.prototype._rebuild.call(this);
  74109. };
  74110. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74111. var numSamples = this.samples;
  74112. var result = [];
  74113. var vector, scale;
  74114. var rand = function (min, max) {
  74115. return Math.random() * (max - min) + min;
  74116. };
  74117. var i = 0;
  74118. while (i < numSamples) {
  74119. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74120. vector.normalize();
  74121. scale = i / numSamples;
  74122. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74123. vector.scaleInPlace(scale);
  74124. result.push(vector.x, vector.y, vector.z);
  74125. i++;
  74126. }
  74127. return result;
  74128. };
  74129. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74130. var _this = this;
  74131. var numSamples = this.samples;
  74132. this._sampleSphere = this._generateHemisphere();
  74133. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74134. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74135. "base", "range", "projection", "near", "far", "texelSize",
  74136. "xViewport", "yViewport", "maxZ", "minZAspect"
  74137. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74138. this._ssaoPostProcess.onApply = function (effect) {
  74139. if (_this._firstUpdate) {
  74140. effect.setArray3("sampleSphere", _this._sampleSphere);
  74141. effect.setFloat("randTextureTiles", 4.0);
  74142. }
  74143. if (!_this._scene.activeCamera) {
  74144. return;
  74145. }
  74146. effect.setFloat("samplesFactor", 1 / _this.samples);
  74147. effect.setFloat("totalStrength", _this.totalStrength);
  74148. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74149. effect.setFloat("radius", _this.radius);
  74150. effect.setFloat("maxZ", _this.maxZ);
  74151. effect.setFloat("minZAspect", _this.minZAspect);
  74152. effect.setFloat("base", _this.base);
  74153. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74154. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74155. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74156. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74157. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74158. effect.setTexture("textureSampler", _this._depthTexture);
  74159. effect.setTexture("normalSampler", _this._normalTexture);
  74160. effect.setTexture("randomSampler", _this._randomTexture);
  74161. };
  74162. };
  74163. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74164. var _this = this;
  74165. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74166. this._ssaoCombinePostProcess.onApply = function (effect) {
  74167. var viewport = _this._scene.activeCamera.viewport;
  74168. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74169. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74170. };
  74171. };
  74172. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74173. var size = 512;
  74174. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74175. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74176. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74177. var context = this._randomTexture.getContext();
  74178. var rand = function (min, max) {
  74179. return Math.random() * (max - min) + min;
  74180. };
  74181. var randVector = BABYLON.Vector3.Zero();
  74182. for (var x = 0; x < size; x++) {
  74183. for (var y = 0; y < size; y++) {
  74184. randVector.x = rand(0.0, 1.0);
  74185. randVector.y = rand(0.0, 1.0);
  74186. randVector.z = 0.0;
  74187. randVector.normalize();
  74188. randVector.scaleInPlace(255);
  74189. randVector.x = Math.floor(randVector.x);
  74190. randVector.y = Math.floor(randVector.y);
  74191. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74192. context.fillRect(x, y, 1, 1);
  74193. }
  74194. }
  74195. this._randomTexture.update(false);
  74196. };
  74197. /**
  74198. * Serialize the rendering pipeline (Used when exporting)
  74199. * @returns the serialized object
  74200. */
  74201. SSAO2RenderingPipeline.prototype.serialize = function () {
  74202. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74203. serializationObject.customType = "SSAO2RenderingPipeline";
  74204. return serializationObject;
  74205. };
  74206. /**
  74207. * Parse the serialized pipeline
  74208. * @param source Source pipeline.
  74209. * @param scene The scene to load the pipeline to.
  74210. * @param rootUrl The URL of the serialized pipeline.
  74211. * @returns An instantiated pipeline from the serialized object.
  74212. */
  74213. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74214. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74215. };
  74216. __decorate([
  74217. BABYLON.serialize()
  74218. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74219. __decorate([
  74220. BABYLON.serialize()
  74221. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74222. __decorate([
  74223. BABYLON.serialize()
  74224. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74225. __decorate([
  74226. BABYLON.serialize("samples")
  74227. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74228. __decorate([
  74229. BABYLON.serialize()
  74230. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74231. __decorate([
  74232. BABYLON.serialize("expensiveBlur")
  74233. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74234. __decorate([
  74235. BABYLON.serialize()
  74236. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74237. __decorate([
  74238. BABYLON.serialize()
  74239. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74240. return SSAO2RenderingPipeline;
  74241. }(BABYLON.PostProcessRenderPipeline));
  74242. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74243. })(BABYLON || (BABYLON = {}));
  74244. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74245. // BABYLON.JS Chromatic Aberration GLSL Shader
  74246. // Author: Olivier Guyot
  74247. // Separates very slightly R, G and B colors on the edges of the screen
  74248. // Inspired by Francois Tarlier & Martins Upitis
  74249. var BABYLON;
  74250. (function (BABYLON) {
  74251. var LensRenderingPipeline = /** @class */ (function (_super) {
  74252. __extends(LensRenderingPipeline, _super);
  74253. /**
  74254. * @constructor
  74255. *
  74256. * Effect parameters are as follow:
  74257. * {
  74258. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74259. * edge_blur: number; // from 0 to x (1 for realism)
  74260. * distortion: number; // from 0 to x (1 for realism)
  74261. * grain_amount: number; // from 0 to 1
  74262. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74263. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74264. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74265. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74266. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74267. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74268. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74269. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74270. * }
  74271. * Note: if an effect parameter is unset, effect is disabled
  74272. *
  74273. * @param {string} name - The rendering pipeline name
  74274. * @param {object} parameters - An object containing all parameters (see above)
  74275. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74276. * @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)
  74277. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74278. */
  74279. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74280. if (ratio === void 0) { ratio = 1.0; }
  74281. var _this = _super.call(this, scene.getEngine(), name) || this;
  74282. // Lens effects can be of the following:
  74283. // - chromatic aberration (slight shift of RGB colors)
  74284. // - blur on the edge of the lens
  74285. // - lens distortion
  74286. // - depth-of-field blur & highlights enhancing
  74287. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74288. // - grain effect (noise or custom texture)
  74289. // Two additional texture samplers are needed:
  74290. // - depth map (for depth-of-field)
  74291. // - grain texture
  74292. /**
  74293. * The chromatic aberration PostProcess id in the pipeline
  74294. */
  74295. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74296. /**
  74297. * The highlights enhancing PostProcess id in the pipeline
  74298. */
  74299. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74300. /**
  74301. * The depth-of-field PostProcess id in the pipeline
  74302. */
  74303. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74304. _this._scene = scene;
  74305. // Fetch texture samplers
  74306. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74307. if (parameters.grain_texture) {
  74308. _this._grainTexture = parameters.grain_texture;
  74309. }
  74310. else {
  74311. _this._createGrainTexture();
  74312. }
  74313. // save parameters
  74314. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74315. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74316. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74317. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74318. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74319. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74320. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74321. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74322. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74323. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74324. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74325. // Create effects
  74326. _this._createChromaticAberrationPostProcess(ratio);
  74327. _this._createHighlightsPostProcess(ratio);
  74328. _this._createDepthOfFieldPostProcess(ratio / 4);
  74329. // Set up pipeline
  74330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74331. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74332. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74333. if (_this._highlightsGain === -1) {
  74334. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74335. }
  74336. // Finish
  74337. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74338. if (cameras) {
  74339. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74340. }
  74341. return _this;
  74342. }
  74343. // public methods (self explanatory)
  74344. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74345. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74346. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74347. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74348. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74349. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74350. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74351. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74352. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74353. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74354. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74355. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74356. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74357. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74358. };
  74359. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74360. this._highlightsPostProcess.updateEffect();
  74361. };
  74362. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74363. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74364. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74365. this._highlightsGain = amount;
  74366. };
  74367. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74368. if (this._highlightsGain === -1) {
  74369. this._highlightsGain = 1.0;
  74370. }
  74371. this._highlightsThreshold = amount;
  74372. };
  74373. LensRenderingPipeline.prototype.disableHighlights = function () {
  74374. this._highlightsGain = -1;
  74375. };
  74376. /**
  74377. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74378. */
  74379. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74380. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74381. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74382. this._chromaticAberrationPostProcess = null;
  74383. this._highlightsPostProcess = null;
  74384. this._depthOfFieldPostProcess = null;
  74385. this._grainTexture.dispose();
  74386. if (disableDepthRender)
  74387. this._scene.disableDepthRenderer();
  74388. };
  74389. // colors shifting and distortion
  74390. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74391. var _this = this;
  74392. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74393. [], // samplers
  74394. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74395. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74396. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74397. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74398. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74399. effect.setFloat('radialIntensity', 1);
  74400. effect.setFloat2('direction', 17, 17);
  74401. effect.setFloat2('centerPosition', 0.5, 0.5);
  74402. };
  74403. };
  74404. // highlights enhancing
  74405. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74406. var _this = this;
  74407. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74408. [], // samplers
  74409. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74410. this._highlightsPostProcess.onApply = function (effect) {
  74411. effect.setFloat('gain', _this._highlightsGain);
  74412. effect.setFloat('threshold', _this._highlightsThreshold);
  74413. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74414. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74415. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74416. };
  74417. };
  74418. // colors shifting and distortion
  74419. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74420. var _this = this;
  74421. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74422. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74423. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74424. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74425. this._depthOfFieldPostProcess.onApply = function (effect) {
  74426. effect.setTexture("depthSampler", _this._depthTexture);
  74427. effect.setTexture("grainSampler", _this._grainTexture);
  74428. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74429. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74430. effect.setFloat('grain_amount', _this._grainAmount);
  74431. effect.setBool('blur_noise', _this._blurNoise);
  74432. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74433. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74434. effect.setFloat('distortion', _this._distortion);
  74435. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74436. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74437. effect.setFloat('aperture', _this._dofAperture);
  74438. effect.setFloat('darken', _this._dofDarken);
  74439. effect.setFloat('edge_blur', _this._edgeBlur);
  74440. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74441. if (_this._scene.activeCamera) {
  74442. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74443. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74444. }
  74445. };
  74446. };
  74447. // creates a black and white random noise texture, 512x512
  74448. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74449. var size = 512;
  74450. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74451. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74452. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74453. var context = this._grainTexture.getContext();
  74454. var rand = function (min, max) {
  74455. return Math.random() * (max - min) + min;
  74456. };
  74457. var value;
  74458. for (var x = 0; x < size; x++) {
  74459. for (var y = 0; y < size; y++) {
  74460. value = Math.floor(rand(0.42, 0.58) * 255);
  74461. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74462. context.fillRect(x, y, 1, 1);
  74463. }
  74464. }
  74465. this._grainTexture.update(false);
  74466. };
  74467. return LensRenderingPipeline;
  74468. }(BABYLON.PostProcessRenderPipeline));
  74469. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74470. })(BABYLON || (BABYLON = {}));
  74471. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74472. var BABYLON;
  74473. (function (BABYLON) {
  74474. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74475. __extends(StandardRenderingPipeline, _super);
  74476. /**
  74477. * @constructor
  74478. * @param {string} name - The rendering pipeline name
  74479. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74480. * @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)
  74481. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74482. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74483. */
  74484. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74485. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74486. var _this = _super.call(this, scene.getEngine(), name) || this;
  74487. _this.downSampleX4PostProcess = null;
  74488. _this.brightPassPostProcess = null;
  74489. _this.blurHPostProcesses = [];
  74490. _this.blurVPostProcesses = [];
  74491. _this.textureAdderPostProcess = null;
  74492. _this.volumetricLightPostProcess = null;
  74493. _this.volumetricLightSmoothXPostProcess = null;
  74494. _this.volumetricLightSmoothYPostProcess = null;
  74495. _this.volumetricLightMergePostProces = null;
  74496. _this.volumetricLightFinalPostProcess = null;
  74497. _this.luminancePostProcess = null;
  74498. _this.luminanceDownSamplePostProcesses = [];
  74499. _this.hdrPostProcess = null;
  74500. _this.textureAdderFinalPostProcess = null;
  74501. _this.lensFlareFinalPostProcess = null;
  74502. _this.hdrFinalPostProcess = null;
  74503. _this.lensFlarePostProcess = null;
  74504. _this.lensFlareComposePostProcess = null;
  74505. _this.motionBlurPostProcess = null;
  74506. _this.depthOfFieldPostProcess = null;
  74507. // Values
  74508. _this.brightThreshold = 1.0;
  74509. _this.blurWidth = 512.0;
  74510. _this.horizontalBlur = false;
  74511. _this.exposure = 1.0;
  74512. _this.lensTexture = null;
  74513. _this.volumetricLightCoefficient = 0.2;
  74514. _this.volumetricLightPower = 4.0;
  74515. _this.volumetricLightBlurScale = 64.0;
  74516. _this.sourceLight = null;
  74517. _this.hdrMinimumLuminance = 1.0;
  74518. _this.hdrDecreaseRate = 0.5;
  74519. _this.hdrIncreaseRate = 0.5;
  74520. _this.lensColorTexture = null;
  74521. _this.lensFlareStrength = 20.0;
  74522. _this.lensFlareGhostDispersal = 1.4;
  74523. _this.lensFlareHaloWidth = 0.7;
  74524. _this.lensFlareDistortionStrength = 16.0;
  74525. _this.lensStarTexture = null;
  74526. _this.lensFlareDirtTexture = null;
  74527. _this.depthOfFieldDistance = 10.0;
  74528. _this.depthOfFieldBlurWidth = 64.0;
  74529. _this.motionStrength = 1.0;
  74530. // IAnimatable
  74531. _this.animations = [];
  74532. _this._currentDepthOfFieldSource = null;
  74533. _this._hdrCurrentLuminance = 1.0;
  74534. // Getters and setters
  74535. _this._bloomEnabled = true;
  74536. _this._depthOfFieldEnabled = false;
  74537. _this._vlsEnabled = false;
  74538. _this._lensFlareEnabled = false;
  74539. _this._hdrEnabled = false;
  74540. _this._motionBlurEnabled = false;
  74541. _this._motionBlurSamples = 64.0;
  74542. _this._volumetricLightStepsCount = 50.0;
  74543. _this._cameras = cameras || [];
  74544. // Initialize
  74545. _this._scene = scene;
  74546. _this._basePostProcess = originalPostProcess;
  74547. _this._ratio = ratio;
  74548. // Misc
  74549. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74550. // Finish
  74551. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74552. _this._buildPipeline();
  74553. return _this;
  74554. }
  74555. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74556. get: function () {
  74557. return this._bloomEnabled;
  74558. },
  74559. set: function (enabled) {
  74560. if (this._bloomEnabled === enabled) {
  74561. return;
  74562. }
  74563. this._bloomEnabled = enabled;
  74564. this._buildPipeline();
  74565. },
  74566. enumerable: true,
  74567. configurable: true
  74568. });
  74569. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74570. get: function () {
  74571. return this._depthOfFieldEnabled;
  74572. },
  74573. set: function (enabled) {
  74574. if (this._depthOfFieldEnabled === enabled) {
  74575. return;
  74576. }
  74577. this._depthOfFieldEnabled = enabled;
  74578. this._buildPipeline();
  74579. },
  74580. enumerable: true,
  74581. configurable: true
  74582. });
  74583. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74584. get: function () {
  74585. return this._lensFlareEnabled;
  74586. },
  74587. set: function (enabled) {
  74588. if (this._lensFlareEnabled === enabled) {
  74589. return;
  74590. }
  74591. this._lensFlareEnabled = enabled;
  74592. this._buildPipeline();
  74593. },
  74594. enumerable: true,
  74595. configurable: true
  74596. });
  74597. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74598. get: function () {
  74599. return this._hdrEnabled;
  74600. },
  74601. set: function (enabled) {
  74602. if (this._hdrEnabled === enabled) {
  74603. return;
  74604. }
  74605. this._hdrEnabled = enabled;
  74606. this._buildPipeline();
  74607. },
  74608. enumerable: true,
  74609. configurable: true
  74610. });
  74611. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74612. get: function () {
  74613. return this._vlsEnabled;
  74614. },
  74615. set: function (enabled) {
  74616. if (this._vlsEnabled === enabled) {
  74617. return;
  74618. }
  74619. if (enabled) {
  74620. var geometry = this._scene.enableGeometryBufferRenderer();
  74621. if (!geometry) {
  74622. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74623. return;
  74624. }
  74625. }
  74626. this._vlsEnabled = enabled;
  74627. this._buildPipeline();
  74628. },
  74629. enumerable: true,
  74630. configurable: true
  74631. });
  74632. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74633. get: function () {
  74634. return this._motionBlurEnabled;
  74635. },
  74636. set: function (enabled) {
  74637. if (this._motionBlurEnabled === enabled) {
  74638. return;
  74639. }
  74640. this._motionBlurEnabled = enabled;
  74641. this._buildPipeline();
  74642. },
  74643. enumerable: true,
  74644. configurable: true
  74645. });
  74646. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74647. get: function () {
  74648. return this._volumetricLightStepsCount;
  74649. },
  74650. set: function (count) {
  74651. if (this.volumetricLightPostProcess) {
  74652. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74653. }
  74654. this._volumetricLightStepsCount = count;
  74655. },
  74656. enumerable: true,
  74657. configurable: true
  74658. });
  74659. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74660. get: function () {
  74661. return this._motionBlurSamples;
  74662. },
  74663. set: function (samples) {
  74664. if (this.motionBlurPostProcess) {
  74665. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74666. }
  74667. this._motionBlurSamples = samples;
  74668. },
  74669. enumerable: true,
  74670. configurable: true
  74671. });
  74672. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74673. var _this = this;
  74674. var ratio = this._ratio;
  74675. var scene = this._scene;
  74676. this._disposePostProcesses();
  74677. this._reset();
  74678. // Create pass post-process
  74679. if (!this._basePostProcess) {
  74680. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74681. this.originalPostProcess.onApply = function (effect) {
  74682. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74683. };
  74684. }
  74685. else {
  74686. this.originalPostProcess = this._basePostProcess;
  74687. }
  74688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74689. this._currentDepthOfFieldSource = this.originalPostProcess;
  74690. if (this._bloomEnabled) {
  74691. // Create down sample X4 post-process
  74692. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74693. // Create bright pass post-process
  74694. this._createBrightPassPostProcess(scene, ratio / 2);
  74695. // Create gaussian blur post-processes (down sampling blurs)
  74696. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74697. // Create texture adder post-process
  74698. this._createTextureAdderPostProcess(scene, ratio);
  74699. // Create depth-of-field source post-process
  74700. 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);
  74701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74702. }
  74703. if (this._vlsEnabled) {
  74704. // Create volumetric light
  74705. this._createVolumetricLightPostProcess(scene, ratio);
  74706. // Create volumetric light final post-process
  74707. 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);
  74708. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74709. }
  74710. if (this._lensFlareEnabled) {
  74711. // Create lens flare post-process
  74712. this._createLensFlarePostProcess(scene, ratio);
  74713. // Create depth-of-field source post-process post lens-flare and disable it now
  74714. 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);
  74715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74716. }
  74717. if (this._hdrEnabled) {
  74718. // Create luminance
  74719. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74720. // Create HDR
  74721. this._createHdrPostProcess(scene, ratio);
  74722. // Create depth-of-field source post-process post hdr and disable it now
  74723. 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);
  74724. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74725. }
  74726. if (this._depthOfFieldEnabled) {
  74727. // Create gaussian blur used by depth-of-field
  74728. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74729. // Create depth-of-field post-process
  74730. this._createDepthOfFieldPostProcess(scene, ratio);
  74731. }
  74732. if (this._motionBlurEnabled) {
  74733. // Create motion blur post-process
  74734. this._createMotionBlurPostProcess(scene, ratio);
  74735. }
  74736. if (this._cameras !== null) {
  74737. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74738. }
  74739. };
  74740. // Down Sample X4 Post-Processs
  74741. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74742. var _this = this;
  74743. var downSampleX4Offsets = new Array(32);
  74744. 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);
  74745. this.downSampleX4PostProcess.onApply = function (effect) {
  74746. var id = 0;
  74747. var width = _this.downSampleX4PostProcess.width;
  74748. var height = _this.downSampleX4PostProcess.height;
  74749. for (var i = -2; i < 2; i++) {
  74750. for (var j = -2; j < 2; j++) {
  74751. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74752. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74753. id += 2;
  74754. }
  74755. }
  74756. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74757. };
  74758. // Add to pipeline
  74759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74760. };
  74761. // Brightpass Post-Process
  74762. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74763. var _this = this;
  74764. var brightOffsets = new Array(8);
  74765. 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);
  74766. this.brightPassPostProcess.onApply = function (effect) {
  74767. var sU = (1.0 / _this.brightPassPostProcess.width);
  74768. var sV = (1.0 / _this.brightPassPostProcess.height);
  74769. brightOffsets[0] = -0.5 * sU;
  74770. brightOffsets[1] = 0.5 * sV;
  74771. brightOffsets[2] = 0.5 * sU;
  74772. brightOffsets[3] = 0.5 * sV;
  74773. brightOffsets[4] = -0.5 * sU;
  74774. brightOffsets[5] = -0.5 * sV;
  74775. brightOffsets[6] = 0.5 * sU;
  74776. brightOffsets[7] = -0.5 * sV;
  74777. effect.setArray2("dsOffsets", brightOffsets);
  74778. effect.setFloat("brightThreshold", _this.brightThreshold);
  74779. };
  74780. // Add to pipeline
  74781. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74782. };
  74783. // Create blur H&V post-processes
  74784. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74785. var _this = this;
  74786. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74787. var engine = scene.getEngine();
  74788. 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);
  74789. 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);
  74790. blurX.onActivateObservable.add(function () {
  74791. var dw = blurX.width / engine.getRenderWidth();
  74792. blurX.kernel = _this[blurWidthKey] * dw;
  74793. });
  74794. blurY.onActivateObservable.add(function () {
  74795. var dw = blurY.height / engine.getRenderHeight();
  74796. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74797. });
  74798. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74800. this.blurHPostProcesses.push(blurX);
  74801. this.blurVPostProcesses.push(blurY);
  74802. };
  74803. // Create texture adder post-process
  74804. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74805. var _this = this;
  74806. 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);
  74807. this.textureAdderPostProcess.onApply = function (effect) {
  74808. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74809. effect.setTexture("lensSampler", _this.lensTexture);
  74810. effect.setFloat("exposure", _this.exposure);
  74811. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74812. };
  74813. // Add to pipeline
  74814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74815. };
  74816. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74817. var _this = this;
  74818. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74819. geometryRenderer.enablePosition = true;
  74820. var geometry = geometryRenderer.getGBuffer();
  74821. // Base post-process
  74822. 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));
  74823. var depthValues = BABYLON.Vector2.Zero();
  74824. this.volumetricLightPostProcess.onApply = function (effect) {
  74825. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74826. var generator = _this.sourceLight.getShadowGenerator();
  74827. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74828. effect.setTexture("positionSampler", geometry.textures[2]);
  74829. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74830. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74831. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74832. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74833. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74834. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74835. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74836. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74837. effect.setVector2("depthValues", depthValues);
  74838. }
  74839. };
  74840. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74841. // Smooth
  74842. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74843. // Merge
  74844. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74845. this.volumetricLightMergePostProces.onApply = function (effect) {
  74846. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74847. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74848. };
  74849. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74850. };
  74851. // Create luminance
  74852. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74853. var _this = this;
  74854. // Create luminance
  74855. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74856. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74857. var offsets = [];
  74858. this.luminancePostProcess.onApply = function (effect) {
  74859. var sU = (1.0 / _this.luminancePostProcess.width);
  74860. var sV = (1.0 / _this.luminancePostProcess.height);
  74861. offsets[0] = -0.5 * sU;
  74862. offsets[1] = 0.5 * sV;
  74863. offsets[2] = 0.5 * sU;
  74864. offsets[3] = 0.5 * sV;
  74865. offsets[4] = -0.5 * sU;
  74866. offsets[5] = -0.5 * sV;
  74867. offsets[6] = 0.5 * sU;
  74868. offsets[7] = -0.5 * sV;
  74869. effect.setArray2("lumOffsets", offsets);
  74870. };
  74871. // Add to pipeline
  74872. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74873. // Create down sample luminance
  74874. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74875. var size = Math.pow(3, i);
  74876. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74877. if (i === 0) {
  74878. defines += "#define FINAL_DOWN_SAMPLER";
  74879. }
  74880. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74881. this.luminanceDownSamplePostProcesses.push(postProcess);
  74882. }
  74883. // Create callbacks and add effects
  74884. var lastLuminance = this.luminancePostProcess;
  74885. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74886. var downSampleOffsets = new Array(18);
  74887. pp.onApply = function (effect) {
  74888. if (!lastLuminance) {
  74889. return;
  74890. }
  74891. var id = 0;
  74892. for (var x = -1; x < 2; x++) {
  74893. for (var y = -1; y < 2; y++) {
  74894. downSampleOffsets[id] = x / lastLuminance.width;
  74895. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74896. id += 2;
  74897. }
  74898. }
  74899. effect.setArray2("dsOffsets", downSampleOffsets);
  74900. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74901. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74902. lastLuminance = _this.luminancePostProcess;
  74903. }
  74904. else {
  74905. lastLuminance = pp;
  74906. }
  74907. };
  74908. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74909. pp.onAfterRender = function (effect) {
  74910. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74911. 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);
  74912. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74913. };
  74914. }
  74915. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74916. });
  74917. };
  74918. // Create HDR post-process
  74919. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74920. var _this = this;
  74921. 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);
  74922. var outputLiminance = 1;
  74923. var time = 0;
  74924. var lastTime = 0;
  74925. this.hdrPostProcess.onApply = function (effect) {
  74926. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74927. time += scene.getEngine().getDeltaTime();
  74928. if (outputLiminance < 0) {
  74929. outputLiminance = _this._hdrCurrentLuminance;
  74930. }
  74931. else {
  74932. var dt = (lastTime - time) / 1000.0;
  74933. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74934. outputLiminance += _this.hdrDecreaseRate * dt;
  74935. }
  74936. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74937. outputLiminance -= _this.hdrIncreaseRate * dt;
  74938. }
  74939. else {
  74940. outputLiminance = _this._hdrCurrentLuminance;
  74941. }
  74942. }
  74943. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74944. effect.setFloat("averageLuminance", outputLiminance);
  74945. lastTime = time;
  74946. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74947. };
  74948. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74949. };
  74950. // Create lens flare post-process
  74951. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74952. var _this = this;
  74953. 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);
  74954. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74955. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74956. 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);
  74957. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74958. var resolution = new BABYLON.Vector2(0, 0);
  74959. // Lens flare
  74960. this.lensFlarePostProcess.onApply = function (effect) {
  74961. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74962. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74963. effect.setFloat("strength", _this.lensFlareStrength);
  74964. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74965. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74966. // Shift
  74967. resolution.x = _this.lensFlarePostProcess.width;
  74968. resolution.y = _this.lensFlarePostProcess.height;
  74969. effect.setVector2("resolution", resolution);
  74970. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74971. };
  74972. // Compose
  74973. 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);
  74974. 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);
  74975. this.lensFlareComposePostProcess.onApply = function (effect) {
  74976. if (!_this._scene.activeCamera) {
  74977. return;
  74978. }
  74979. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74980. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74981. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74982. // Lens start rotation matrix
  74983. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74984. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74985. 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));
  74986. camRot *= 4.0;
  74987. 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);
  74988. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74989. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74990. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74991. };
  74992. };
  74993. // Create depth-of-field post-process
  74994. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74995. var _this = this;
  74996. 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);
  74997. this.depthOfFieldPostProcess.onApply = function (effect) {
  74998. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74999. effect.setTexture("depthSampler", _this._getDepthTexture());
  75000. effect.setFloat("distance", _this.depthOfFieldDistance);
  75001. };
  75002. // Add to pipeline
  75003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75004. };
  75005. // Create motion blur post-process
  75006. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75007. var _this = this;
  75008. 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);
  75009. var motionScale = 0;
  75010. var prevViewProjection = BABYLON.Matrix.Identity();
  75011. var invViewProjection = BABYLON.Matrix.Identity();
  75012. var viewProjection = BABYLON.Matrix.Identity();
  75013. var screenSize = BABYLON.Vector2.Zero();
  75014. this.motionBlurPostProcess.onApply = function (effect) {
  75015. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75016. viewProjection.invertToRef(invViewProjection);
  75017. effect.setMatrix("inverseViewProjection", invViewProjection);
  75018. effect.setMatrix("prevViewProjection", prevViewProjection);
  75019. prevViewProjection = viewProjection;
  75020. screenSize.x = _this.motionBlurPostProcess.width;
  75021. screenSize.y = _this.motionBlurPostProcess.height;
  75022. effect.setVector2("screenSize", screenSize);
  75023. motionScale = scene.getEngine().getFps() / 60.0;
  75024. effect.setFloat("motionScale", motionScale);
  75025. effect.setFloat("motionStrength", _this.motionStrength);
  75026. effect.setTexture("depthSampler", _this._getDepthTexture());
  75027. };
  75028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75029. };
  75030. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75031. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75032. var renderer = this._scene.enableGeometryBufferRenderer();
  75033. return renderer.getGBuffer().textures[0];
  75034. }
  75035. return this._scene.enableDepthRenderer().getDepthMap();
  75036. };
  75037. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75038. for (var i = 0; i < this._cameras.length; i++) {
  75039. var camera = this._cameras[i];
  75040. if (this.originalPostProcess) {
  75041. this.originalPostProcess.dispose(camera);
  75042. }
  75043. if (this.downSampleX4PostProcess) {
  75044. this.downSampleX4PostProcess.dispose(camera);
  75045. }
  75046. if (this.brightPassPostProcess) {
  75047. this.brightPassPostProcess.dispose(camera);
  75048. }
  75049. if (this.textureAdderPostProcess) {
  75050. this.textureAdderPostProcess.dispose(camera);
  75051. }
  75052. if (this.textureAdderFinalPostProcess) {
  75053. this.textureAdderFinalPostProcess.dispose(camera);
  75054. }
  75055. if (this.volumetricLightPostProcess) {
  75056. this.volumetricLightPostProcess.dispose(camera);
  75057. }
  75058. if (this.volumetricLightSmoothXPostProcess) {
  75059. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75060. }
  75061. if (this.volumetricLightSmoothYPostProcess) {
  75062. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75063. }
  75064. if (this.volumetricLightMergePostProces) {
  75065. this.volumetricLightMergePostProces.dispose(camera);
  75066. }
  75067. if (this.volumetricLightFinalPostProcess) {
  75068. this.volumetricLightFinalPostProcess.dispose(camera);
  75069. }
  75070. if (this.lensFlarePostProcess) {
  75071. this.lensFlarePostProcess.dispose(camera);
  75072. }
  75073. if (this.lensFlareComposePostProcess) {
  75074. this.lensFlareComposePostProcess.dispose(camera);
  75075. }
  75076. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75077. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75078. }
  75079. if (this.luminancePostProcess) {
  75080. this.luminancePostProcess.dispose(camera);
  75081. }
  75082. if (this.hdrPostProcess) {
  75083. this.hdrPostProcess.dispose(camera);
  75084. }
  75085. if (this.hdrFinalPostProcess) {
  75086. this.hdrFinalPostProcess.dispose(camera);
  75087. }
  75088. if (this.depthOfFieldPostProcess) {
  75089. this.depthOfFieldPostProcess.dispose(camera);
  75090. }
  75091. if (this.motionBlurPostProcess) {
  75092. this.motionBlurPostProcess.dispose(camera);
  75093. }
  75094. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75095. this.blurHPostProcesses[j].dispose(camera);
  75096. }
  75097. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75098. this.blurVPostProcesses[j].dispose(camera);
  75099. }
  75100. }
  75101. this.originalPostProcess = null;
  75102. this.downSampleX4PostProcess = null;
  75103. this.brightPassPostProcess = null;
  75104. this.textureAdderPostProcess = null;
  75105. this.textureAdderFinalPostProcess = null;
  75106. this.volumetricLightPostProcess = null;
  75107. this.volumetricLightSmoothXPostProcess = null;
  75108. this.volumetricLightSmoothYPostProcess = null;
  75109. this.volumetricLightMergePostProces = null;
  75110. this.volumetricLightFinalPostProcess = null;
  75111. this.lensFlarePostProcess = null;
  75112. this.lensFlareComposePostProcess = null;
  75113. this.luminancePostProcess = null;
  75114. this.hdrPostProcess = null;
  75115. this.hdrFinalPostProcess = null;
  75116. this.depthOfFieldPostProcess = null;
  75117. this.motionBlurPostProcess = null;
  75118. this.luminanceDownSamplePostProcesses = [];
  75119. this.blurHPostProcesses = [];
  75120. this.blurVPostProcesses = [];
  75121. };
  75122. /**
  75123. * Dispose of the pipeline and stop all post processes
  75124. */
  75125. StandardRenderingPipeline.prototype.dispose = function () {
  75126. this._disposePostProcesses();
  75127. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75128. _super.prototype.dispose.call(this);
  75129. };
  75130. /**
  75131. * Serialize the rendering pipeline (Used when exporting)
  75132. * @returns the serialized object
  75133. */
  75134. StandardRenderingPipeline.prototype.serialize = function () {
  75135. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75136. if (this.sourceLight) {
  75137. serializationObject.sourceLightId = this.sourceLight.id;
  75138. }
  75139. serializationObject.customType = "StandardRenderingPipeline";
  75140. return serializationObject;
  75141. };
  75142. /**
  75143. * Parse the serialized pipeline
  75144. * @param source Source pipeline.
  75145. * @param scene The scene to load the pipeline to.
  75146. * @param rootUrl The URL of the serialized pipeline.
  75147. * @returns An instantiated pipeline from the serialized object.
  75148. */
  75149. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75150. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75151. if (source.sourceLightId) {
  75152. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75153. }
  75154. return p;
  75155. };
  75156. // Luminance steps
  75157. StandardRenderingPipeline.LuminanceSteps = 6;
  75158. __decorate([
  75159. BABYLON.serialize()
  75160. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75161. __decorate([
  75162. BABYLON.serialize()
  75163. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75164. __decorate([
  75165. BABYLON.serialize()
  75166. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75167. __decorate([
  75168. BABYLON.serialize()
  75169. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75170. __decorate([
  75171. BABYLON.serializeAsTexture("lensTexture")
  75172. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75173. __decorate([
  75174. BABYLON.serialize()
  75175. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75176. __decorate([
  75177. BABYLON.serialize()
  75178. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75179. __decorate([
  75180. BABYLON.serialize()
  75181. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75182. __decorate([
  75183. BABYLON.serialize()
  75184. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75185. __decorate([
  75186. BABYLON.serialize()
  75187. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75188. __decorate([
  75189. BABYLON.serialize()
  75190. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75191. __decorate([
  75192. BABYLON.serializeAsTexture("lensColorTexture")
  75193. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75194. __decorate([
  75195. BABYLON.serialize()
  75196. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75197. __decorate([
  75198. BABYLON.serialize()
  75199. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75200. __decorate([
  75201. BABYLON.serialize()
  75202. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75203. __decorate([
  75204. BABYLON.serialize()
  75205. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75206. __decorate([
  75207. BABYLON.serializeAsTexture("lensStarTexture")
  75208. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75209. __decorate([
  75210. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75211. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75212. __decorate([
  75213. BABYLON.serialize()
  75214. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75215. __decorate([
  75216. BABYLON.serialize()
  75217. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75218. __decorate([
  75219. BABYLON.serialize()
  75220. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75221. __decorate([
  75222. BABYLON.serialize()
  75223. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75224. __decorate([
  75225. BABYLON.serialize()
  75226. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75227. __decorate([
  75228. BABYLON.serialize()
  75229. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75230. __decorate([
  75231. BABYLON.serialize()
  75232. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75233. __decorate([
  75234. BABYLON.serialize()
  75235. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75236. __decorate([
  75237. BABYLON.serialize()
  75238. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75239. __decorate([
  75240. BABYLON.serialize()
  75241. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75242. __decorate([
  75243. BABYLON.serialize()
  75244. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75245. __decorate([
  75246. BABYLON.serialize()
  75247. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75248. return StandardRenderingPipeline;
  75249. }(BABYLON.PostProcessRenderPipeline));
  75250. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75251. })(BABYLON || (BABYLON = {}));
  75252. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75253. var BABYLON;
  75254. (function (BABYLON) {
  75255. var FxaaPostProcess = /** @class */ (function (_super) {
  75256. __extends(FxaaPostProcess, _super);
  75257. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75258. if (camera === void 0) { camera = null; }
  75259. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75260. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75261. var defines = _this._getDefines();
  75262. _this.updateEffect(defines);
  75263. _this.onApplyObservable.add(function (effect) {
  75264. var texelSize = _this.texelSize;
  75265. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75266. });
  75267. return _this;
  75268. }
  75269. FxaaPostProcess.prototype._getDefines = function () {
  75270. var engine = this.getEngine();
  75271. if (!engine) {
  75272. return null;
  75273. }
  75274. var glInfo = engine.getGlInfo();
  75275. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75276. return "#define MALI 1\n";
  75277. }
  75278. return null;
  75279. };
  75280. return FxaaPostProcess;
  75281. }(BABYLON.PostProcess));
  75282. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75283. })(BABYLON || (BABYLON = {}));
  75284. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75285. var BABYLON;
  75286. (function (BABYLON) {
  75287. /**
  75288. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75289. */
  75290. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75291. __extends(ChromaticAberrationPostProcess, _super);
  75292. /**
  75293. * Creates a new instance ChromaticAberrationPostProcess
  75294. * @param name The name of the effect.
  75295. * @param screenWidth The width of the screen to apply the effect on.
  75296. * @param screenHeight The height of the screen to apply the effect on.
  75297. * @param options The required width/height ratio to downsize to before computing the render pass.
  75298. * @param camera The camera to apply the render pass to.
  75299. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75300. * @param engine The engine which the post process will be applied. (default: current engine)
  75301. * @param reusable If the post process can be reused on the same frame. (default: false)
  75302. * @param textureType Type of textures used when performing the post process. (default: 0)
  75303. * @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)
  75304. */
  75305. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75306. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75307. if (blockCompilation === void 0) { blockCompilation = false; }
  75308. 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;
  75309. /**
  75310. * The amount of seperation of rgb channels (default: 30)
  75311. */
  75312. _this.aberrationAmount = 30;
  75313. /**
  75314. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75315. */
  75316. _this.radialIntensity = 0;
  75317. /**
  75318. * 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))
  75319. */
  75320. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75321. /**
  75322. * 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))
  75323. */
  75324. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75325. _this.onApplyObservable.add(function (effect) {
  75326. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75327. effect.setFloat('screen_width', screenWidth);
  75328. effect.setFloat('screen_height', screenHeight);
  75329. effect.setFloat('radialIntensity', _this.radialIntensity);
  75330. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75331. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75332. });
  75333. return _this;
  75334. }
  75335. return ChromaticAberrationPostProcess;
  75336. }(BABYLON.PostProcess));
  75337. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75338. })(BABYLON || (BABYLON = {}));
  75339. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75340. var BABYLON;
  75341. (function (BABYLON) {
  75342. /**
  75343. * The GrainPostProcess adds noise to the image at mid luminance levels
  75344. */
  75345. var GrainPostProcess = /** @class */ (function (_super) {
  75346. __extends(GrainPostProcess, _super);
  75347. /**
  75348. * Creates a new instance of @see GrainPostProcess
  75349. * @param name The name of the effect.
  75350. * @param options The required width/height ratio to downsize to before computing the render pass.
  75351. * @param camera The camera to apply the render pass to.
  75352. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75353. * @param engine The engine which the post process will be applied. (default: current engine)
  75354. * @param reusable If the post process can be reused on the same frame. (default: false)
  75355. * @param textureType Type of textures used when performing the post process. (default: 0)
  75356. * @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)
  75357. */
  75358. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75359. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75360. if (blockCompilation === void 0) { blockCompilation = false; }
  75361. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75362. /**
  75363. * The intensity of the grain added (default: 30)
  75364. */
  75365. _this.intensity = 30;
  75366. /**
  75367. * If the grain should be randomized on every frame
  75368. */
  75369. _this.animated = false;
  75370. _this.onApplyObservable.add(function (effect) {
  75371. effect.setFloat('intensity', _this.intensity);
  75372. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75373. });
  75374. return _this;
  75375. }
  75376. return GrainPostProcess;
  75377. }(BABYLON.PostProcess));
  75378. BABYLON.GrainPostProcess = GrainPostProcess;
  75379. })(BABYLON || (BABYLON = {}));
  75380. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75381. var BABYLON;
  75382. (function (BABYLON) {
  75383. /**
  75384. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75385. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75386. */
  75387. var SharpenPostProcess = /** @class */ (function (_super) {
  75388. __extends(SharpenPostProcess, _super);
  75389. /**
  75390. * Creates a new instance ConvolutionPostProcess
  75391. * @param name The name of the effect.
  75392. * @param options The required width/height ratio to downsize to before computing the render pass.
  75393. * @param camera The camera to apply the render pass to.
  75394. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75395. * @param engine The engine which the post process will be applied. (default: current engine)
  75396. * @param reusable If the post process can be reused on the same frame. (default: false)
  75397. * @param textureType Type of textures used when performing the post process. (default: 0)
  75398. * @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)
  75399. */
  75400. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75401. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75402. if (blockCompilation === void 0) { blockCompilation = false; }
  75403. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75404. /**
  75405. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75406. */
  75407. _this.colorAmount = 1.0;
  75408. /**
  75409. * How much sharpness should be applied (default: 0.3)
  75410. */
  75411. _this.edgeAmount = 0.3;
  75412. _this.onApply = function (effect) {
  75413. effect.setFloat2("screenSize", _this.width, _this.height);
  75414. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75415. };
  75416. return _this;
  75417. }
  75418. return SharpenPostProcess;
  75419. }(BABYLON.PostProcess));
  75420. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75421. })(BABYLON || (BABYLON = {}));
  75422. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75423. var BABYLON;
  75424. (function (BABYLON) {
  75425. /**
  75426. * The Blur Post Process which blurs an image based on a kernel and direction.
  75427. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75428. */
  75429. var BlurPostProcess = /** @class */ (function (_super) {
  75430. __extends(BlurPostProcess, _super);
  75431. /**
  75432. * Creates a new instance BlurPostProcess
  75433. * @param name The name of the effect.
  75434. * @param direction The direction in which to blur the image.
  75435. * @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.
  75436. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75437. * @param camera The camera to apply the render pass to.
  75438. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75439. * @param engine The engine which the post process will be applied. (default: current engine)
  75440. * @param reusable If the post process can be reused on the same frame. (default: false)
  75441. * @param textureType Type of textures used when performing the post process. (default: 0)
  75442. * @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)
  75443. */
  75444. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75446. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75447. if (defines === void 0) { defines = ""; }
  75448. if (blockCompilation === void 0) { blockCompilation = false; }
  75449. 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;
  75450. _this.direction = direction;
  75451. _this.blockCompilation = blockCompilation;
  75452. _this._packedFloat = false;
  75453. _this._staticDefines = "";
  75454. _this._staticDefines = defines;
  75455. _this.onApplyObservable.add(function (effect) {
  75456. if (_this._outputTexture) {
  75457. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75458. }
  75459. else {
  75460. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75461. }
  75462. });
  75463. _this.kernel = kernel;
  75464. return _this;
  75465. }
  75466. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75467. /**
  75468. * Gets the length in pixels of the blur sample region
  75469. */
  75470. get: function () {
  75471. return this._idealKernel;
  75472. },
  75473. /**
  75474. * Sets the length in pixels of the blur sample region
  75475. */
  75476. set: function (v) {
  75477. if (this._idealKernel === v) {
  75478. return;
  75479. }
  75480. v = Math.max(v, 1);
  75481. this._idealKernel = v;
  75482. this._kernel = this._nearestBestKernel(v);
  75483. if (!this.blockCompilation) {
  75484. this._updateParameters();
  75485. }
  75486. },
  75487. enumerable: true,
  75488. configurable: true
  75489. });
  75490. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75491. /**
  75492. * Gets wether or not the blur is unpacking/repacking floats
  75493. */
  75494. get: function () {
  75495. return this._packedFloat;
  75496. },
  75497. /**
  75498. * Sets wether or not the blur needs to unpack/repack floats
  75499. */
  75500. set: function (v) {
  75501. if (this._packedFloat === v) {
  75502. return;
  75503. }
  75504. this._packedFloat = v;
  75505. if (!this.blockCompilation) {
  75506. this._updateParameters();
  75507. }
  75508. },
  75509. enumerable: true,
  75510. configurable: true
  75511. });
  75512. /**
  75513. * Updates the effect with the current post process compile time values and recompiles the shader.
  75514. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75515. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75516. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75517. * @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
  75518. * @param onCompiled Called when the shader has been compiled.
  75519. * @param onError Called if there is an error when compiling a shader.
  75520. */
  75521. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75522. if (defines === void 0) { defines = null; }
  75523. if (uniforms === void 0) { uniforms = null; }
  75524. if (samplers === void 0) { samplers = null; }
  75525. this._updateParameters(onCompiled, onError);
  75526. };
  75527. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75528. // Generate sampling offsets and weights
  75529. var N = this._kernel;
  75530. var centerIndex = (N - 1) / 2;
  75531. // Generate Gaussian sampling weights over kernel
  75532. var offsets = [];
  75533. var weights = [];
  75534. var totalWeight = 0;
  75535. for (var i = 0; i < N; i++) {
  75536. var u = i / (N - 1);
  75537. var w = this._gaussianWeight(u * 2.0 - 1);
  75538. offsets[i] = (i - centerIndex);
  75539. weights[i] = w;
  75540. totalWeight += w;
  75541. }
  75542. // Normalize weights
  75543. for (var i = 0; i < weights.length; i++) {
  75544. weights[i] /= totalWeight;
  75545. }
  75546. // Optimize: combine samples to take advantage of hardware linear sampling
  75547. // Walk from left to center, combining pairs (symmetrically)
  75548. var linearSamplingWeights = [];
  75549. var linearSamplingOffsets = [];
  75550. var linearSamplingMap = [];
  75551. for (var i = 0; i <= centerIndex; i += 2) {
  75552. var j = Math.min(i + 1, Math.floor(centerIndex));
  75553. var singleCenterSample = i === j;
  75554. if (singleCenterSample) {
  75555. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75556. }
  75557. else {
  75558. var sharedCell = j === centerIndex;
  75559. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75560. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75561. if (offsetLinear === 0) {
  75562. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75563. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75564. }
  75565. else {
  75566. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75567. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75568. }
  75569. }
  75570. }
  75571. for (var i = 0; i < linearSamplingMap.length; i++) {
  75572. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75573. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75574. }
  75575. // Replace with optimized
  75576. offsets = linearSamplingOffsets;
  75577. weights = linearSamplingWeights;
  75578. // Generate shaders
  75579. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75580. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75581. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75582. var defines = "";
  75583. defines += this._staticDefines;
  75584. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75585. if (this._staticDefines.indexOf("DOF") != -1) {
  75586. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75587. varyingCount--;
  75588. }
  75589. for (var i = 0; i < varyingCount; i++) {
  75590. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75591. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75592. }
  75593. var depCount = 0;
  75594. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75595. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75596. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75597. depCount++;
  75598. }
  75599. if (this.packedFloat) {
  75600. defines += "#define PACKEDFLOAT 1";
  75601. }
  75602. this.blockCompilation = false;
  75603. _super.prototype.updateEffect.call(this, defines, null, null, {
  75604. varyingCount: varyingCount,
  75605. depCount: depCount
  75606. }, onCompiled, onError);
  75607. };
  75608. /**
  75609. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75610. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75611. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75612. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75613. * The gaps between physical kernels are compensated for in the weighting of the samples
  75614. * @param idealKernel Ideal blur kernel.
  75615. * @return Nearest best kernel.
  75616. */
  75617. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75618. var v = Math.round(idealKernel);
  75619. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75620. var k = _a[_i];
  75621. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75622. return Math.max(k, 3);
  75623. }
  75624. }
  75625. return Math.max(v, 3);
  75626. };
  75627. /**
  75628. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75629. * @param x The point on the Gaussian distribution to sample.
  75630. * @return the value of the Gaussian function at x.
  75631. */
  75632. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75633. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75634. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75635. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75636. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75637. // truncated at around 1.3% of peak strength.
  75638. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75639. var sigma = (1 / 3);
  75640. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75641. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75642. var weight = (1.0 / denominator) * Math.exp(exponent);
  75643. return weight;
  75644. };
  75645. /**
  75646. * Generates a string that can be used as a floating point number in GLSL.
  75647. * @param x Value to print.
  75648. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75649. * @return GLSL float string.
  75650. */
  75651. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75652. if (decimalFigures === void 0) { decimalFigures = 8; }
  75653. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75654. };
  75655. return BlurPostProcess;
  75656. }(BABYLON.PostProcess));
  75657. BABYLON.BlurPostProcess = BlurPostProcess;
  75658. })(BABYLON || (BABYLON = {}));
  75659. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75660. var BABYLON;
  75661. (function (BABYLON) {
  75662. /**
  75663. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75664. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75665. * based on samples that have a large difference in distance than the center pixel.
  75666. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75667. */
  75668. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75669. __extends(DepthOfFieldBlurPostProcess, _super);
  75670. /**
  75671. * Creates a new instance CircleOfConfusionPostProcess
  75672. * @param name The name of the effect.
  75673. * @param scene The scene the effect belongs to.
  75674. * @param direction The direction the blur should be applied.
  75675. * @param kernel The size of the kernel used to blur.
  75676. * @param options The required width/height ratio to downsize to before computing the render pass.
  75677. * @param camera The camera to apply the render pass to.
  75678. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75679. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75680. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75681. * @param engine The engine which the post process will be applied. (default: current engine)
  75682. * @param reusable If the post process can be reused on the same frame. (default: false)
  75683. * @param textureType Type of textures used when performing the post process. (default: 0)
  75684. * @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)
  75685. */
  75686. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75687. if (imageToBlur === void 0) { imageToBlur = null; }
  75688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75689. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75690. if (blockCompilation === void 0) { blockCompilation = false; }
  75691. 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;
  75692. _this.direction = direction;
  75693. _this.onApplyObservable.add(function (effect) {
  75694. if (imageToBlur != null) {
  75695. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75696. }
  75697. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75698. if (scene.activeCamera) {
  75699. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75700. }
  75701. });
  75702. return _this;
  75703. }
  75704. return DepthOfFieldBlurPostProcess;
  75705. }(BABYLON.BlurPostProcess));
  75706. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75707. })(BABYLON || (BABYLON = {}));
  75708. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75709. var BABYLON;
  75710. (function (BABYLON) {
  75711. /**
  75712. * Options to be set when merging outputs from the default pipeline.
  75713. */
  75714. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75715. function DepthOfFieldMergePostProcessOptions() {
  75716. }
  75717. return DepthOfFieldMergePostProcessOptions;
  75718. }());
  75719. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75720. /**
  75721. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75722. */
  75723. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75724. __extends(DepthOfFieldMergePostProcess, _super);
  75725. /**
  75726. * Creates a new instance of DepthOfFieldMergePostProcess
  75727. * @param name The name of the effect.
  75728. * @param originalFromInput Post process which's input will be used for the merge.
  75729. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75730. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75731. * @param options The required width/height ratio to downsize to before computing the render pass.
  75732. * @param camera The camera to apply the render pass to.
  75733. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75734. * @param engine The engine which the post process will be applied. (default: current engine)
  75735. * @param reusable If the post process can be reused on the same frame. (default: false)
  75736. * @param textureType Type of textures used when performing the post process. (default: 0)
  75737. * @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)
  75738. */
  75739. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75740. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75741. if (blockCompilation === void 0) { blockCompilation = false; }
  75742. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75743. _this.blurSteps = blurSteps;
  75744. _this.onApplyObservable.add(function (effect) {
  75745. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75746. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75747. blurSteps.forEach(function (step, index) {
  75748. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75749. });
  75750. });
  75751. if (!blockCompilation) {
  75752. _this.updateEffect();
  75753. }
  75754. return _this;
  75755. }
  75756. /**
  75757. * Updates the effect with the current post process compile time values and recompiles the shader.
  75758. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75759. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75760. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75761. * @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
  75762. * @param onCompiled Called when the shader has been compiled.
  75763. * @param onError Called if there is an error when compiling a shader.
  75764. */
  75765. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75766. if (defines === void 0) { defines = null; }
  75767. if (uniforms === void 0) { uniforms = null; }
  75768. if (samplers === void 0) { samplers = null; }
  75769. if (!defines) {
  75770. defines = "";
  75771. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75772. }
  75773. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75774. };
  75775. return DepthOfFieldMergePostProcess;
  75776. }(BABYLON.PostProcess));
  75777. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75778. })(BABYLON || (BABYLON = {}));
  75779. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75780. var BABYLON;
  75781. (function (BABYLON) {
  75782. /**
  75783. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75784. */
  75785. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75786. __extends(CircleOfConfusionPostProcess, _super);
  75787. /**
  75788. * Creates a new instance CircleOfConfusionPostProcess
  75789. * @param name The name of the effect.
  75790. * @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.
  75791. * @param options The required width/height ratio to downsize to before computing the render pass.
  75792. * @param camera The camera to apply the render pass to.
  75793. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75794. * @param engine The engine which the post process will be applied. (default: current engine)
  75795. * @param reusable If the post process can be reused on the same frame. (default: false)
  75796. * @param textureType Type of textures used when performing the post process. (default: 0)
  75797. * @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)
  75798. */
  75799. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75800. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75801. if (blockCompilation === void 0) { blockCompilation = false; }
  75802. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75803. /**
  75804. * 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.
  75805. */
  75806. _this.lensSize = 50;
  75807. /**
  75808. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75809. */
  75810. _this.fStop = 1.4;
  75811. /**
  75812. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75813. */
  75814. _this.focusDistance = 2000;
  75815. /**
  75816. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75817. */
  75818. _this.focalLength = 50;
  75819. _this._depthTexture = null;
  75820. _this._depthTexture = depthTexture;
  75821. _this.onApplyObservable.add(function (effect) {
  75822. if (!_this._depthTexture) {
  75823. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75824. return;
  75825. }
  75826. effect.setTexture("depthSampler", _this._depthTexture);
  75827. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75828. var aperture = _this.lensSize / _this.fStop;
  75829. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75830. effect.setFloat('focusDistance', _this.focusDistance);
  75831. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75832. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75833. });
  75834. return _this;
  75835. }
  75836. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75837. /**
  75838. * 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.
  75839. */
  75840. set: function (value) {
  75841. this._depthTexture = value;
  75842. },
  75843. enumerable: true,
  75844. configurable: true
  75845. });
  75846. return CircleOfConfusionPostProcess;
  75847. }(BABYLON.PostProcess));
  75848. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75849. })(BABYLON || (BABYLON = {}));
  75850. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75851. var BABYLON;
  75852. (function (BABYLON) {
  75853. /**
  75854. * Specifies the level of max blur that should be applied when using the depth of field effect
  75855. */
  75856. var DepthOfFieldEffectBlurLevel;
  75857. (function (DepthOfFieldEffectBlurLevel) {
  75858. /**
  75859. * Subtle blur
  75860. */
  75861. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75862. /**
  75863. * Medium blur
  75864. */
  75865. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75866. /**
  75867. * Large blur
  75868. */
  75869. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75870. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75871. ;
  75872. /**
  75873. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75874. */
  75875. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75876. __extends(DepthOfFieldEffect, _super);
  75877. /**
  75878. * Creates a new instance DepthOfFieldEffect
  75879. * @param scene The scene the effect belongs to.
  75880. * @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.
  75881. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75882. * @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)
  75883. */
  75884. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75885. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75886. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75887. if (blockCompilation === void 0) { blockCompilation = false; }
  75888. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75889. return _this._effects;
  75890. }, true) || this;
  75891. /**
  75892. * Internal post processes in depth of field effect
  75893. */
  75894. _this._effects = [];
  75895. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75896. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75897. // 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)
  75898. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75899. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75900. _this._depthOfFieldBlurY = [];
  75901. _this._depthOfFieldBlurX = [];
  75902. var blurCount = 1;
  75903. var kernelSize = 15;
  75904. switch (blurLevel) {
  75905. case DepthOfFieldEffectBlurLevel.High: {
  75906. blurCount = 3;
  75907. kernelSize = 51;
  75908. break;
  75909. }
  75910. case DepthOfFieldEffectBlurLevel.Medium: {
  75911. blurCount = 2;
  75912. kernelSize = 31;
  75913. break;
  75914. }
  75915. default: {
  75916. kernelSize = 15;
  75917. blurCount = 1;
  75918. break;
  75919. }
  75920. }
  75921. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75922. var ratio = 1.0;
  75923. for (var i = 0; i < blurCount; i++) {
  75924. 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);
  75925. blurY.autoClear = false;
  75926. ratio = 0.75 / Math.pow(2, i);
  75927. 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);
  75928. blurX.autoClear = false;
  75929. _this._depthOfFieldBlurY.push(blurY);
  75930. _this._depthOfFieldBlurX.push(blurX);
  75931. }
  75932. // Set all post processes on the effect.
  75933. _this._effects = [_this._circleOfConfusion];
  75934. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75935. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75936. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75937. }
  75938. // Merge blurred images with original image based on circleOfConfusion
  75939. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75940. _this._dofMerge.autoClear = false;
  75941. _this._effects.push(_this._dofMerge);
  75942. return _this;
  75943. }
  75944. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75945. get: function () {
  75946. return this._circleOfConfusion.focalLength;
  75947. },
  75948. /**
  75949. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75950. */
  75951. set: function (value) {
  75952. this._circleOfConfusion.focalLength = value;
  75953. },
  75954. enumerable: true,
  75955. configurable: true
  75956. });
  75957. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75958. get: function () {
  75959. return this._circleOfConfusion.fStop;
  75960. },
  75961. /**
  75962. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75963. */
  75964. set: function (value) {
  75965. this._circleOfConfusion.fStop = value;
  75966. },
  75967. enumerable: true,
  75968. configurable: true
  75969. });
  75970. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75971. get: function () {
  75972. return this._circleOfConfusion.focusDistance;
  75973. },
  75974. /**
  75975. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75976. */
  75977. set: function (value) {
  75978. this._circleOfConfusion.focusDistance = value;
  75979. },
  75980. enumerable: true,
  75981. configurable: true
  75982. });
  75983. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75984. get: function () {
  75985. return this._circleOfConfusion.lensSize;
  75986. },
  75987. /**
  75988. * 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.
  75989. */
  75990. set: function (value) {
  75991. this._circleOfConfusion.lensSize = value;
  75992. },
  75993. enumerable: true,
  75994. configurable: true
  75995. });
  75996. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75997. /**
  75998. * 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.
  75999. */
  76000. set: function (value) {
  76001. this._circleOfConfusion.depthTexture = value;
  76002. },
  76003. enumerable: true,
  76004. configurable: true
  76005. });
  76006. /**
  76007. * Disposes each of the internal effects for a given camera.
  76008. * @param camera The camera to dispose the effect on.
  76009. */
  76010. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76011. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76012. this._effects[effectIndex].dispose(camera);
  76013. }
  76014. };
  76015. /**
  76016. * Internal
  76017. */
  76018. DepthOfFieldEffect.prototype._updateEffects = function () {
  76019. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76020. this._effects[effectIndex].updateEffect();
  76021. }
  76022. };
  76023. /**
  76024. * Internal
  76025. * @returns if all the contained post processes are ready.
  76026. */
  76027. DepthOfFieldEffect.prototype._isReady = function () {
  76028. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76029. if (!this._effects[effectIndex].isReady()) {
  76030. return false;
  76031. }
  76032. }
  76033. return true;
  76034. };
  76035. return DepthOfFieldEffect;
  76036. }(BABYLON.PostProcessRenderEffect));
  76037. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76038. })(BABYLON || (BABYLON = {}));
  76039. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76040. var BABYLON;
  76041. (function (BABYLON) {
  76042. /**
  76043. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76044. */
  76045. var BloomMergePostProcess = /** @class */ (function (_super) {
  76046. __extends(BloomMergePostProcess, _super);
  76047. /**
  76048. * Creates a new instance of @see BloomMergePostProcess
  76049. * @param name The name of the effect.
  76050. * @param originalFromInput Post process which's input will be used for the merge.
  76051. * @param blurred Blurred highlights post process which's output will be used.
  76052. * @param weight Weight of the bloom to be added to the original input.
  76053. * @param options The required width/height ratio to downsize to before computing the render pass.
  76054. * @param camera The camera to apply the render pass to.
  76055. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76056. * @param engine The engine which the post process will be applied. (default: current engine)
  76057. * @param reusable If the post process can be reused on the same frame. (default: false)
  76058. * @param textureType Type of textures used when performing the post process. (default: 0)
  76059. * @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)
  76060. */
  76061. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76062. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76063. if (blockCompilation === void 0) { blockCompilation = false; }
  76064. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76065. _this.weight = weight;
  76066. _this.onApplyObservable.add(function (effect) {
  76067. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76068. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76069. effect.setFloat("bloomWeight", _this.weight);
  76070. });
  76071. if (!blockCompilation) {
  76072. _this.updateEffect();
  76073. }
  76074. return _this;
  76075. }
  76076. return BloomMergePostProcess;
  76077. }(BABYLON.PostProcess));
  76078. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76079. })(BABYLON || (BABYLON = {}));
  76080. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76081. var BABYLON;
  76082. (function (BABYLON) {
  76083. /**
  76084. * 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.
  76085. */
  76086. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76087. __extends(ExtractHighlightsPostProcess, _super);
  76088. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76089. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76090. if (blockCompilation === void 0) { blockCompilation = false; }
  76091. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76092. /**
  76093. * The luminance threshold, pixels below this value will be set to black.
  76094. */
  76095. _this.threshold = 0.9;
  76096. /**
  76097. * Internal
  76098. */
  76099. _this._exposure = 1;
  76100. /**
  76101. * Post process which has the input texture to be used when performing highlight extraction
  76102. */
  76103. _this._inputPostProcess = null;
  76104. _this.onApplyObservable.add(function (effect) {
  76105. if (_this._inputPostProcess) {
  76106. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76107. }
  76108. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76109. effect.setFloat('exposure', _this._exposure);
  76110. });
  76111. return _this;
  76112. }
  76113. return ExtractHighlightsPostProcess;
  76114. }(BABYLON.PostProcess));
  76115. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76116. })(BABYLON || (BABYLON = {}));
  76117. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76118. var BABYLON;
  76119. (function (BABYLON) {
  76120. /**
  76121. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76122. */
  76123. var BloomEffect = /** @class */ (function (_super) {
  76124. __extends(BloomEffect, _super);
  76125. /**
  76126. * Creates a new instance of @see BloomEffect
  76127. * @param scene The scene the effect belongs to.
  76128. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76129. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76130. * @param bloomWeight The the strength of bloom.
  76131. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76132. * @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)
  76133. */
  76134. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76135. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76136. if (blockCompilation === void 0) { blockCompilation = false; }
  76137. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76138. return _this._effects;
  76139. }, true) || this;
  76140. _this.bloomScale = bloomScale;
  76141. /**
  76142. * Internal
  76143. */
  76144. _this._effects = [];
  76145. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76146. _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);
  76147. _this._blurX.alwaysForcePOT = true;
  76148. _this._blurX.autoClear = false;
  76149. _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);
  76150. _this._blurY.alwaysForcePOT = true;
  76151. _this._blurY.autoClear = false;
  76152. _this.kernel = bloomKernel;
  76153. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76154. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76155. _this._merge.autoClear = false;
  76156. _this._effects.push(_this._merge);
  76157. return _this;
  76158. }
  76159. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76160. /**
  76161. * The luminance threshold to find bright areas of the image to bloom.
  76162. */
  76163. get: function () {
  76164. return this._downscale.threshold;
  76165. },
  76166. set: function (value) {
  76167. this._downscale.threshold = value;
  76168. },
  76169. enumerable: true,
  76170. configurable: true
  76171. });
  76172. Object.defineProperty(BloomEffect.prototype, "weight", {
  76173. /**
  76174. * The strength of the bloom.
  76175. */
  76176. get: function () {
  76177. return this._merge.weight;
  76178. },
  76179. set: function (value) {
  76180. this._merge.weight = value;
  76181. },
  76182. enumerable: true,
  76183. configurable: true
  76184. });
  76185. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76186. /**
  76187. * Specifies the size of the bloom blur kernel, relative to the final output size
  76188. */
  76189. get: function () {
  76190. return this._blurX.kernel / this.bloomScale;
  76191. },
  76192. set: function (value) {
  76193. this._blurX.kernel = value * this.bloomScale;
  76194. this._blurY.kernel = value * this.bloomScale;
  76195. },
  76196. enumerable: true,
  76197. configurable: true
  76198. });
  76199. /**
  76200. * Disposes each of the internal effects for a given camera.
  76201. * @param camera The camera to dispose the effect on.
  76202. */
  76203. BloomEffect.prototype.disposeEffects = function (camera) {
  76204. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76205. this._effects[effectIndex].dispose(camera);
  76206. }
  76207. };
  76208. /**
  76209. * Internal
  76210. */
  76211. BloomEffect.prototype._updateEffects = function () {
  76212. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76213. this._effects[effectIndex].updateEffect();
  76214. }
  76215. };
  76216. /**
  76217. * Internal
  76218. * @returns if all the contained post processes are ready.
  76219. */
  76220. BloomEffect.prototype._isReady = function () {
  76221. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76222. if (!this._effects[effectIndex].isReady()) {
  76223. return false;
  76224. }
  76225. }
  76226. return true;
  76227. };
  76228. return BloomEffect;
  76229. }(BABYLON.PostProcessRenderEffect));
  76230. BABYLON.BloomEffect = BloomEffect;
  76231. })(BABYLON || (BABYLON = {}));
  76232. //# sourceMappingURL=babylon.bloomEffect.js.map
  76233. var BABYLON;
  76234. (function (BABYLON) {
  76235. /**
  76236. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76237. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76238. */
  76239. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76240. __extends(DefaultRenderingPipeline, _super);
  76241. /**
  76242. * @constructor
  76243. * @param {string} name - The rendering pipeline name (default: "")
  76244. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76245. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76246. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76247. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76248. */
  76249. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76250. if (name === void 0) { name = ""; }
  76251. if (hdr === void 0) { hdr = true; }
  76252. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76253. if (automaticBuild === void 0) { automaticBuild = true; }
  76254. var _this = _super.call(this, scene.getEngine(), name) || this;
  76255. _this._originalCameras = [];
  76256. /**
  76257. * ID of the sharpen post process,
  76258. */
  76259. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76260. /**
  76261. * ID of the image processing post process;
  76262. */
  76263. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76264. /**
  76265. * ID of the Fast Approximate Anti-Aliasing post process;
  76266. */
  76267. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76268. /**
  76269. * ID of the chromatic aberration post process,
  76270. */
  76271. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76272. /**
  76273. * ID of the grain post process
  76274. */
  76275. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76276. /**
  76277. * Glow post process which adds a glow to emmisive areas of the image
  76278. */
  76279. _this._glowLayer = null;
  76280. /**
  76281. * Animations which can be used to tweak settings over a period of time
  76282. */
  76283. _this.animations = [];
  76284. _this._imageProcessingConfigurationObserver = null;
  76285. // Values
  76286. _this._sharpenEnabled = false;
  76287. _this._bloomEnabled = false;
  76288. _this._depthOfFieldEnabled = false;
  76289. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76290. _this._fxaaEnabled = false;
  76291. _this._imageProcessingEnabled = true;
  76292. _this._bloomScale = 0.5;
  76293. _this._chromaticAberrationEnabled = false;
  76294. _this._grainEnabled = false;
  76295. _this._buildAllowed = true;
  76296. _this._resizeObserver = null;
  76297. _this._hardwareScaleLevel = 1.0;
  76298. _this._bloomKernel = 64;
  76299. /**
  76300. * Specifies the weight of the bloom in the final rendering
  76301. */
  76302. _this._bloomWeight = 0.15;
  76303. /**
  76304. * Specifies the luma threshold for the area that will be blurred by the bloom
  76305. */
  76306. _this._bloomThreshold = 0.9;
  76307. _this._samples = 1;
  76308. _this._hasCleared = false;
  76309. _this._prevPostProcess = null;
  76310. _this._prevPrevPostProcess = null;
  76311. _this._cameras = cameras || scene.cameras;
  76312. _this._originalCameras = _this._cameras.slice();
  76313. _this._buildAllowed = automaticBuild;
  76314. // Initialize
  76315. _this._scene = scene;
  76316. var caps = _this._scene.getEngine().getCaps();
  76317. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76318. // Misc
  76319. if (_this._hdr) {
  76320. if (caps.textureHalfFloatRender) {
  76321. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76322. }
  76323. else if (caps.textureFloatRender) {
  76324. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76325. }
  76326. }
  76327. else {
  76328. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76329. }
  76330. // Attach
  76331. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76332. var engine = _this._scene.getEngine();
  76333. // Create post processes before hand so they can be modified before enabled.
  76334. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76335. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76336. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76337. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76338. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76339. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76340. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76341. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76342. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76343. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76344. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76345. _this.bloomKernel = _this.bloomKernel;
  76346. });
  76347. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76348. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76349. });
  76350. _this._buildPipeline();
  76351. return _this;
  76352. }
  76353. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76354. get: function () {
  76355. return this._sharpenEnabled;
  76356. },
  76357. /**
  76358. * Enable or disable the sharpen process from the pipeline
  76359. */
  76360. set: function (enabled) {
  76361. if (this._sharpenEnabled === enabled) {
  76362. return;
  76363. }
  76364. this._sharpenEnabled = enabled;
  76365. this._buildPipeline();
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76371. /**
  76372. * Specifies the size of the bloom blur kernel, relative to the final output size
  76373. */
  76374. get: function () {
  76375. return this._bloomKernel;
  76376. },
  76377. set: function (value) {
  76378. this._bloomKernel = value;
  76379. this.bloom.kernel = value / this._hardwareScaleLevel;
  76380. },
  76381. enumerable: true,
  76382. configurable: true
  76383. });
  76384. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76385. get: function () {
  76386. return this._bloomWeight;
  76387. },
  76388. /**
  76389. * The strength of the bloom.
  76390. */
  76391. set: function (value) {
  76392. if (this._bloomWeight === value) {
  76393. return;
  76394. }
  76395. this.bloom.weight = value;
  76396. this._bloomWeight = value;
  76397. },
  76398. enumerable: true,
  76399. configurable: true
  76400. });
  76401. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76402. get: function () {
  76403. return this._bloomThreshold;
  76404. },
  76405. /**
  76406. * The strength of the bloom.
  76407. */
  76408. set: function (value) {
  76409. if (this._bloomThreshold === value) {
  76410. return;
  76411. }
  76412. this.bloom.threshold = value;
  76413. this._bloomThreshold = value;
  76414. },
  76415. enumerable: true,
  76416. configurable: true
  76417. });
  76418. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76419. get: function () {
  76420. return this._bloomScale;
  76421. },
  76422. /**
  76423. * The scale of the bloom, lower value will provide better performance.
  76424. */
  76425. set: function (value) {
  76426. if (this._bloomScale === value) {
  76427. return;
  76428. }
  76429. this._bloomScale = value;
  76430. // recreate bloom and dispose old as this setting is not dynamic
  76431. this._rebuildBloom();
  76432. this._buildPipeline();
  76433. },
  76434. enumerable: true,
  76435. configurable: true
  76436. });
  76437. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76438. get: function () {
  76439. return this._bloomEnabled;
  76440. },
  76441. /**
  76442. * Enable or disable the bloom from the pipeline
  76443. */
  76444. set: function (enabled) {
  76445. if (this._bloomEnabled === enabled) {
  76446. return;
  76447. }
  76448. this._bloomEnabled = enabled;
  76449. this._buildPipeline();
  76450. },
  76451. enumerable: true,
  76452. configurable: true
  76453. });
  76454. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76455. // recreate bloom and dispose old as this setting is not dynamic
  76456. var oldBloom = this.bloom;
  76457. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76458. this.bloom.threshold = oldBloom.threshold;
  76459. for (var i = 0; i < this._cameras.length; i++) {
  76460. oldBloom.disposeEffects(this._cameras[i]);
  76461. }
  76462. };
  76463. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76464. /**
  76465. * If the depth of field is enabled.
  76466. */
  76467. get: function () {
  76468. return this._depthOfFieldEnabled;
  76469. },
  76470. set: function (enabled) {
  76471. if (this._depthOfFieldEnabled === enabled) {
  76472. return;
  76473. }
  76474. this._depthOfFieldEnabled = enabled;
  76475. this._buildPipeline();
  76476. },
  76477. enumerable: true,
  76478. configurable: true
  76479. });
  76480. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76481. /**
  76482. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76483. */
  76484. get: function () {
  76485. return this._depthOfFieldBlurLevel;
  76486. },
  76487. set: function (value) {
  76488. if (this._depthOfFieldBlurLevel === value) {
  76489. return;
  76490. }
  76491. this._depthOfFieldBlurLevel = value;
  76492. // recreate dof and dispose old as this setting is not dynamic
  76493. var oldDof = this.depthOfField;
  76494. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76495. this.depthOfField.focalLength = oldDof.focalLength;
  76496. this.depthOfField.focusDistance = oldDof.focusDistance;
  76497. this.depthOfField.fStop = oldDof.fStop;
  76498. this.depthOfField.lensSize = oldDof.lensSize;
  76499. for (var i = 0; i < this._cameras.length; i++) {
  76500. oldDof.disposeEffects(this._cameras[i]);
  76501. }
  76502. this._buildPipeline();
  76503. },
  76504. enumerable: true,
  76505. configurable: true
  76506. });
  76507. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76508. get: function () {
  76509. return this._fxaaEnabled;
  76510. },
  76511. /**
  76512. * If the anti aliasing is enabled.
  76513. */
  76514. set: function (enabled) {
  76515. if (this._fxaaEnabled === enabled) {
  76516. return;
  76517. }
  76518. this._fxaaEnabled = enabled;
  76519. this._buildPipeline();
  76520. },
  76521. enumerable: true,
  76522. configurable: true
  76523. });
  76524. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76525. get: function () {
  76526. return this._samples;
  76527. },
  76528. /**
  76529. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76530. */
  76531. set: function (sampleCount) {
  76532. if (this._samples === sampleCount) {
  76533. return;
  76534. }
  76535. this._samples = sampleCount;
  76536. this._buildPipeline();
  76537. },
  76538. enumerable: true,
  76539. configurable: true
  76540. });
  76541. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76542. get: function () {
  76543. return this._imageProcessingEnabled;
  76544. },
  76545. /**
  76546. * If image processing is enabled.
  76547. */
  76548. set: function (enabled) {
  76549. if (this._imageProcessingEnabled === enabled) {
  76550. return;
  76551. }
  76552. this._imageProcessingEnabled = enabled;
  76553. this._buildPipeline();
  76554. },
  76555. enumerable: true,
  76556. configurable: true
  76557. });
  76558. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76559. get: function () {
  76560. return this._glowLayer == null;
  76561. },
  76562. /**
  76563. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76564. */
  76565. set: function (enabled) {
  76566. if (enabled && !this._glowLayer) {
  76567. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76568. }
  76569. else if (!enabled && this._glowLayer) {
  76570. this._glowLayer.dispose();
  76571. this._glowLayer = null;
  76572. }
  76573. },
  76574. enumerable: true,
  76575. configurable: true
  76576. });
  76577. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76578. get: function () {
  76579. return this._chromaticAberrationEnabled;
  76580. },
  76581. /**
  76582. * Enable or disable the chromaticAberration process from the pipeline
  76583. */
  76584. set: function (enabled) {
  76585. if (this._chromaticAberrationEnabled === enabled) {
  76586. return;
  76587. }
  76588. this._chromaticAberrationEnabled = enabled;
  76589. this._buildPipeline();
  76590. },
  76591. enumerable: true,
  76592. configurable: true
  76593. });
  76594. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76595. get: function () {
  76596. return this._grainEnabled;
  76597. },
  76598. /**
  76599. * Enable or disable the grain process from the pipeline
  76600. */
  76601. set: function (enabled) {
  76602. if (this._grainEnabled === enabled) {
  76603. return;
  76604. }
  76605. this._grainEnabled = enabled;
  76606. this._buildPipeline();
  76607. },
  76608. enumerable: true,
  76609. configurable: true
  76610. });
  76611. /**
  76612. * Force the compilation of the entire pipeline.
  76613. */
  76614. DefaultRenderingPipeline.prototype.prepare = function () {
  76615. var previousState = this._buildAllowed;
  76616. this._buildAllowed = true;
  76617. this._buildPipeline();
  76618. this._buildAllowed = previousState;
  76619. };
  76620. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76621. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76622. if (this._hasCleared) {
  76623. postProcess.autoClear = false;
  76624. }
  76625. else {
  76626. postProcess.autoClear = true;
  76627. this._scene.autoClear = false;
  76628. this._hasCleared = true;
  76629. }
  76630. if (!skipTextureSharing) {
  76631. if (this._prevPrevPostProcess) {
  76632. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76633. }
  76634. else {
  76635. postProcess.useOwnOutput();
  76636. }
  76637. if (this._prevPostProcess) {
  76638. this._prevPrevPostProcess = this._prevPostProcess;
  76639. }
  76640. this._prevPostProcess = postProcess;
  76641. }
  76642. };
  76643. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76644. var _this = this;
  76645. if (!this._buildAllowed) {
  76646. return;
  76647. }
  76648. this._scene.autoClear = true;
  76649. var engine = this._scene.getEngine();
  76650. this._disposePostProcesses();
  76651. if (this._cameras !== null) {
  76652. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76653. // get back cameras to be used to reattach pipeline
  76654. this._cameras = this._originalCameras.slice();
  76655. }
  76656. this._reset();
  76657. this._prevPostProcess = null;
  76658. this._prevPrevPostProcess = null;
  76659. this._hasCleared = false;
  76660. if (this.depthOfFieldEnabled) {
  76661. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76662. this.depthOfField.depthTexture = depthTexture;
  76663. if (!this.depthOfField._isReady()) {
  76664. this.depthOfField._updateEffects();
  76665. }
  76666. this.addEffect(this.depthOfField);
  76667. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76668. }
  76669. if (this.bloomEnabled) {
  76670. if (!this.bloom._isReady()) {
  76671. this.bloom._updateEffects();
  76672. }
  76673. this.addEffect(this.bloom);
  76674. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76675. }
  76676. if (this._imageProcessingEnabled) {
  76677. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76678. if (this._hdr) {
  76679. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76680. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76681. }
  76682. else {
  76683. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76684. }
  76685. }
  76686. if (this.sharpenEnabled) {
  76687. if (!this.sharpen.isReady()) {
  76688. this.sharpen.updateEffect();
  76689. }
  76690. this.addEffect(this._sharpenEffect);
  76691. this._setAutoClearAndTextureSharing(this.sharpen);
  76692. }
  76693. if (this.grainEnabled) {
  76694. if (!this.grain.isReady()) {
  76695. this.grain.updateEffect();
  76696. }
  76697. this.addEffect(this._grainEffect);
  76698. this._setAutoClearAndTextureSharing(this.grain);
  76699. }
  76700. if (this.chromaticAberrationEnabled) {
  76701. if (!this.chromaticAberration.isReady()) {
  76702. this.chromaticAberration.updateEffect();
  76703. }
  76704. this.addEffect(this._chromaticAberrationEffect);
  76705. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76706. }
  76707. if (this.fxaaEnabled) {
  76708. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76709. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76710. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76711. }
  76712. if (this._cameras !== null) {
  76713. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76714. }
  76715. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76716. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76717. }
  76718. };
  76719. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76720. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76721. for (var i = 0; i < this._cameras.length; i++) {
  76722. var camera = this._cameras[i];
  76723. if (this.imageProcessing) {
  76724. this.imageProcessing.dispose(camera);
  76725. }
  76726. if (this.fxaa) {
  76727. this.fxaa.dispose(camera);
  76728. }
  76729. // These are created in the constructor and should not be disposed on every pipeline change
  76730. if (disposeNonRecreated) {
  76731. if (this.sharpen) {
  76732. this.sharpen.dispose(camera);
  76733. }
  76734. if (this.depthOfField) {
  76735. this.depthOfField.disposeEffects(camera);
  76736. }
  76737. if (this.bloom) {
  76738. this.bloom.disposeEffects(camera);
  76739. }
  76740. if (this.chromaticAberration) {
  76741. this.chromaticAberration.dispose(camera);
  76742. }
  76743. if (this.grain) {
  76744. this.grain.dispose(camera);
  76745. }
  76746. if (this._glowLayer) {
  76747. this._glowLayer.dispose();
  76748. }
  76749. }
  76750. }
  76751. this.imageProcessing = null;
  76752. this.fxaa = null;
  76753. if (disposeNonRecreated) {
  76754. this.sharpen = null;
  76755. this._sharpenEffect = null;
  76756. this.depthOfField = null;
  76757. this.bloom = null;
  76758. this.chromaticAberration = null;
  76759. this._chromaticAberrationEffect = null;
  76760. this.grain = null;
  76761. this._grainEffect = null;
  76762. this._glowLayer = null;
  76763. }
  76764. };
  76765. /**
  76766. * Dispose of the pipeline and stop all post processes
  76767. */
  76768. DefaultRenderingPipeline.prototype.dispose = function () {
  76769. this._disposePostProcesses(true);
  76770. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76771. this._scene.autoClear = true;
  76772. if (this._resizeObserver) {
  76773. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76774. this._resizeObserver = null;
  76775. }
  76776. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76777. _super.prototype.dispose.call(this);
  76778. };
  76779. /**
  76780. * Serialize the rendering pipeline (Used when exporting)
  76781. * @returns the serialized object
  76782. */
  76783. DefaultRenderingPipeline.prototype.serialize = function () {
  76784. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76785. serializationObject.customType = "DefaultRenderingPipeline";
  76786. return serializationObject;
  76787. };
  76788. /**
  76789. * Parse the serialized pipeline
  76790. * @param source Source pipeline.
  76791. * @param scene The scene to load the pipeline to.
  76792. * @param rootUrl The URL of the serialized pipeline.
  76793. * @returns An instantiated pipeline from the serialized object.
  76794. */
  76795. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76796. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76797. };
  76798. __decorate([
  76799. BABYLON.serialize()
  76800. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76801. __decorate([
  76802. BABYLON.serialize()
  76803. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76804. __decorate([
  76805. BABYLON.serialize()
  76806. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76807. __decorate([
  76808. BABYLON.serialize()
  76809. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76810. __decorate([
  76811. BABYLON.serialize()
  76812. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76813. __decorate([
  76814. BABYLON.serialize()
  76815. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76816. __decorate([
  76817. BABYLON.serialize()
  76818. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76819. __decorate([
  76820. BABYLON.serialize()
  76821. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76822. __decorate([
  76823. BABYLON.serialize()
  76824. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76825. __decorate([
  76826. BABYLON.serialize()
  76827. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76828. __decorate([
  76829. BABYLON.serialize()
  76830. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76831. __decorate([
  76832. BABYLON.serialize()
  76833. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76834. __decorate([
  76835. BABYLON.serialize()
  76836. ], DefaultRenderingPipeline.prototype, "samples", null);
  76837. __decorate([
  76838. BABYLON.serialize()
  76839. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76840. __decorate([
  76841. BABYLON.serialize()
  76842. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76843. __decorate([
  76844. BABYLON.serialize()
  76845. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76846. __decorate([
  76847. BABYLON.serialize()
  76848. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76849. return DefaultRenderingPipeline;
  76850. }(BABYLON.PostProcessRenderPipeline));
  76851. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76852. })(BABYLON || (BABYLON = {}));
  76853. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76854. var BABYLON;
  76855. (function (BABYLON) {
  76856. /**
  76857. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76858. */
  76859. var GeometryBufferRenderer = /** @class */ (function () {
  76860. /**
  76861. * Creates a new G Buffer for the scene
  76862. * @param scene The scene the buffer belongs to
  76863. * @param ratio How big is the buffer related to the main canvas.
  76864. */
  76865. function GeometryBufferRenderer(scene, ratio) {
  76866. if (ratio === void 0) { ratio = 1; }
  76867. this._enablePosition = false;
  76868. this._scene = scene;
  76869. this._ratio = ratio;
  76870. // Render target
  76871. this._createRenderTargets();
  76872. }
  76873. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76874. /**
  76875. * Set the render list (meshes to be rendered) used in the G buffer.
  76876. */
  76877. set: function (meshes) {
  76878. this._multiRenderTarget.renderList = meshes;
  76879. },
  76880. enumerable: true,
  76881. configurable: true
  76882. });
  76883. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76884. /**
  76885. * Gets wether or not G buffer are supported by the running hardware.
  76886. * This requires draw buffer supports
  76887. */
  76888. get: function () {
  76889. return this._multiRenderTarget.isSupported;
  76890. },
  76891. enumerable: true,
  76892. configurable: true
  76893. });
  76894. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76895. /**
  76896. * Gets wether or not position are enabled for the G buffer.
  76897. */
  76898. get: function () {
  76899. return this._enablePosition;
  76900. },
  76901. /**
  76902. * Sets wether or not position are enabled for the G buffer.
  76903. */
  76904. set: function (enable) {
  76905. this._enablePosition = enable;
  76906. this.dispose();
  76907. this._createRenderTargets();
  76908. },
  76909. enumerable: true,
  76910. configurable: true
  76911. });
  76912. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76913. /**
  76914. * Gets the scene associated with the buffer.
  76915. */
  76916. get: function () {
  76917. return this._scene;
  76918. },
  76919. enumerable: true,
  76920. configurable: true
  76921. });
  76922. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76923. /**
  76924. * Gets the ratio used by the buffer during its creation.
  76925. * How big is the buffer related to the main canvas.
  76926. */
  76927. get: function () {
  76928. return this._ratio;
  76929. },
  76930. enumerable: true,
  76931. configurable: true
  76932. });
  76933. /**
  76934. * Checks wether everything is ready to render a submesh to the G buffer.
  76935. * @param subMesh the submesh to check readiness for
  76936. * @param useInstances is the mesh drawn using instance or not
  76937. * @returns true if ready otherwise false
  76938. */
  76939. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76940. var material = subMesh.getMaterial();
  76941. if (material && material.disableDepthWrite) {
  76942. return false;
  76943. }
  76944. var defines = [];
  76945. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76946. var mesh = subMesh.getMesh();
  76947. // Alpha test
  76948. if (material && material.needAlphaTesting()) {
  76949. defines.push("#define ALPHATEST");
  76950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76951. attribs.push(BABYLON.VertexBuffer.UVKind);
  76952. defines.push("#define UV1");
  76953. }
  76954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76955. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76956. defines.push("#define UV2");
  76957. }
  76958. }
  76959. // Buffers
  76960. if (this._enablePosition) {
  76961. defines.push("#define POSITION");
  76962. }
  76963. // Bones
  76964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76965. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76966. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76967. if (mesh.numBoneInfluencers > 4) {
  76968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76970. }
  76971. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76972. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76973. }
  76974. else {
  76975. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76976. }
  76977. // Instances
  76978. if (useInstances) {
  76979. defines.push("#define INSTANCES");
  76980. attribs.push("world0");
  76981. attribs.push("world1");
  76982. attribs.push("world2");
  76983. attribs.push("world3");
  76984. }
  76985. // Get correct effect
  76986. var join = defines.join("\n");
  76987. if (this._cachedDefines !== join) {
  76988. this._cachedDefines = join;
  76989. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76990. }
  76991. return this._effect.isReady();
  76992. };
  76993. /**
  76994. * Gets the current underlying G Buffer.
  76995. * @returns the buffer
  76996. */
  76997. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76998. return this._multiRenderTarget;
  76999. };
  77000. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77001. /**
  77002. * Gets the number of samples used to render the buffer (anti aliasing).
  77003. */
  77004. get: function () {
  77005. return this._multiRenderTarget.samples;
  77006. },
  77007. /**
  77008. * Sets the number of samples used to render the buffer (anti aliasing).
  77009. */
  77010. set: function (value) {
  77011. this._multiRenderTarget.samples = value;
  77012. },
  77013. enumerable: true,
  77014. configurable: true
  77015. });
  77016. /**
  77017. * Disposes the renderer and frees up associated resources.
  77018. */
  77019. GeometryBufferRenderer.prototype.dispose = function () {
  77020. this.getGBuffer().dispose();
  77021. };
  77022. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77023. var _this = this;
  77024. var engine = this._scene.getEngine();
  77025. var count = this._enablePosition ? 3 : 2;
  77026. 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 });
  77027. if (!this.isSupported) {
  77028. return;
  77029. }
  77030. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77031. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77032. this._multiRenderTarget.refreshRate = 1;
  77033. this._multiRenderTarget.renderParticles = false;
  77034. this._multiRenderTarget.renderList = null;
  77035. // set default depth value to 1.0 (far away)
  77036. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77037. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77038. });
  77039. // Custom render function
  77040. var renderSubMesh = function (subMesh) {
  77041. var mesh = subMesh.getRenderingMesh();
  77042. var scene = _this._scene;
  77043. var engine = scene.getEngine();
  77044. var material = subMesh.getMaterial();
  77045. if (!material) {
  77046. return;
  77047. }
  77048. // Culling
  77049. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77050. // Managing instances
  77051. var batch = mesh._getInstancesRenderList(subMesh._id);
  77052. if (batch.mustReturn) {
  77053. return;
  77054. }
  77055. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77056. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77057. engine.enableEffect(_this._effect);
  77058. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77059. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77060. _this._effect.setMatrix("view", scene.getViewMatrix());
  77061. // Alpha test
  77062. if (material && material.needAlphaTesting()) {
  77063. var alphaTexture = material.getAlphaTestTexture();
  77064. if (alphaTexture) {
  77065. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77066. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77067. }
  77068. }
  77069. // Bones
  77070. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77071. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77072. }
  77073. // Draw
  77074. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77075. }
  77076. };
  77077. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77078. var index;
  77079. if (depthOnlySubMeshes.length) {
  77080. engine.setColorWrite(false);
  77081. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77082. renderSubMesh(depthOnlySubMeshes.data[index]);
  77083. }
  77084. engine.setColorWrite(true);
  77085. }
  77086. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77087. renderSubMesh(opaqueSubMeshes.data[index]);
  77088. }
  77089. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77090. renderSubMesh(alphaTestSubMeshes.data[index]);
  77091. }
  77092. };
  77093. };
  77094. return GeometryBufferRenderer;
  77095. }());
  77096. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77097. })(BABYLON || (BABYLON = {}));
  77098. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77099. var BABYLON;
  77100. (function (BABYLON) {
  77101. var RefractionPostProcess = /** @class */ (function (_super) {
  77102. __extends(RefractionPostProcess, _super);
  77103. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77104. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77105. _this.color = color;
  77106. _this.depth = depth;
  77107. _this.colorLevel = colorLevel;
  77108. _this._ownRefractionTexture = true;
  77109. _this.onActivateObservable.add(function (cam) {
  77110. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77111. });
  77112. _this.onApplyObservable.add(function (effect) {
  77113. effect.setColor3("baseColor", _this.color);
  77114. effect.setFloat("depth", _this.depth);
  77115. effect.setFloat("colorLevel", _this.colorLevel);
  77116. effect.setTexture("refractionSampler", _this._refTexture);
  77117. });
  77118. return _this;
  77119. }
  77120. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77121. /**
  77122. * Gets or sets the refraction texture
  77123. * Please note that you are responsible for disposing the texture if you set it manually
  77124. */
  77125. get: function () {
  77126. return this._refTexture;
  77127. },
  77128. set: function (value) {
  77129. if (this._refTexture && this._ownRefractionTexture) {
  77130. this._refTexture.dispose();
  77131. }
  77132. this._refTexture = value;
  77133. this._ownRefractionTexture = false;
  77134. },
  77135. enumerable: true,
  77136. configurable: true
  77137. });
  77138. // Methods
  77139. RefractionPostProcess.prototype.dispose = function (camera) {
  77140. if (this._refTexture && this._ownRefractionTexture) {
  77141. this._refTexture.dispose();
  77142. this._refTexture = null;
  77143. }
  77144. _super.prototype.dispose.call(this, camera);
  77145. };
  77146. return RefractionPostProcess;
  77147. }(BABYLON.PostProcess));
  77148. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77149. })(BABYLON || (BABYLON = {}));
  77150. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77151. var BABYLON;
  77152. (function (BABYLON) {
  77153. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77154. __extends(BlackAndWhitePostProcess, _super);
  77155. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77156. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77157. _this.degree = 1;
  77158. _this.onApplyObservable.add(function (effect) {
  77159. effect.setFloat("degree", _this.degree);
  77160. });
  77161. return _this;
  77162. }
  77163. return BlackAndWhitePostProcess;
  77164. }(BABYLON.PostProcess));
  77165. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77166. })(BABYLON || (BABYLON = {}));
  77167. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77168. var BABYLON;
  77169. (function (BABYLON) {
  77170. /**
  77171. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77172. * input texture to perform effects such as edge detection or sharpening
  77173. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77174. */
  77175. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77176. __extends(ConvolutionPostProcess, _super);
  77177. /**
  77178. * Creates a new instance ConvolutionPostProcess
  77179. * @param name The name of the effect.
  77180. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77181. * @param options The required width/height ratio to downsize to before computing the render pass.
  77182. * @param camera The camera to apply the render pass to.
  77183. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77184. * @param engine The engine which the post process will be applied. (default: current engine)
  77185. * @param reusable If the post process can be reused on the same frame. (default: false)
  77186. * @param textureType Type of textures used when performing the post process. (default: 0)
  77187. */
  77188. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77189. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77190. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77191. _this.kernel = kernel;
  77192. _this.onApply = function (effect) {
  77193. effect.setFloat2("screenSize", _this.width, _this.height);
  77194. effect.setArray("kernel", _this.kernel);
  77195. };
  77196. return _this;
  77197. }
  77198. // Statics
  77199. /**
  77200. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77201. */
  77202. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77203. /**
  77204. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77205. */
  77206. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77207. /**
  77208. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77209. */
  77210. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77211. /**
  77212. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77213. */
  77214. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77215. /**
  77216. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77217. */
  77218. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77219. /**
  77220. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77221. */
  77222. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77223. return ConvolutionPostProcess;
  77224. }(BABYLON.PostProcess));
  77225. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77226. })(BABYLON || (BABYLON = {}));
  77227. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77228. var BABYLON;
  77229. (function (BABYLON) {
  77230. var FilterPostProcess = /** @class */ (function (_super) {
  77231. __extends(FilterPostProcess, _super);
  77232. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77233. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77234. _this.kernelMatrix = kernelMatrix;
  77235. _this.onApply = function (effect) {
  77236. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77237. };
  77238. return _this;
  77239. }
  77240. return FilterPostProcess;
  77241. }(BABYLON.PostProcess));
  77242. BABYLON.FilterPostProcess = FilterPostProcess;
  77243. })(BABYLON || (BABYLON = {}));
  77244. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77245. var BABYLON;
  77246. (function (BABYLON) {
  77247. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77248. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77249. __extends(VolumetricLightScatteringPostProcess, _super);
  77250. /**
  77251. * @constructor
  77252. * @param {string} name - The post-process name
  77253. * @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)
  77254. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77255. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77256. * @param {number} samples - The post-process quality, default 100
  77257. * @param {number} samplingMode - The post-process filtering mode
  77258. * @param {BABYLON.Engine} engine - The babylon engine
  77259. * @param {boolean} reusable - If the post-process is reusable
  77260. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77261. */
  77262. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77263. if (samples === void 0) { samples = 100; }
  77264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77265. 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;
  77266. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77267. /**
  77268. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77269. */
  77270. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77271. /**
  77272. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77273. */
  77274. _this.useCustomMeshPosition = false;
  77275. /**
  77276. * If the post-process should inverse the light scattering direction
  77277. */
  77278. _this.invert = true;
  77279. /**
  77280. * Array containing the excluded meshes not rendered in the internal pass
  77281. */
  77282. _this.excludedMeshes = new Array();
  77283. /**
  77284. * Controls the overall intensity of the post-process
  77285. */
  77286. _this.exposure = 0.3;
  77287. /**
  77288. * Dissipates each sample's contribution in range [0, 1]
  77289. */
  77290. _this.decay = 0.96815;
  77291. /**
  77292. * Controls the overall intensity of each sample
  77293. */
  77294. _this.weight = 0.58767;
  77295. /**
  77296. * Controls the density of each sample
  77297. */
  77298. _this.density = 0.926;
  77299. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77300. engine = scene.getEngine();
  77301. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77302. // Configure mesh
  77303. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77304. // Configure
  77305. _this._createPass(scene, ratio.passRatio || ratio);
  77306. _this.onActivate = function (camera) {
  77307. if (!_this.isSupported) {
  77308. _this.dispose(camera);
  77309. }
  77310. _this.onActivate = null;
  77311. };
  77312. _this.onApplyObservable.add(function (effect) {
  77313. _this._updateMeshScreenCoordinates(scene);
  77314. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77315. effect.setFloat("exposure", _this.exposure);
  77316. effect.setFloat("decay", _this.decay);
  77317. effect.setFloat("weight", _this.weight);
  77318. effect.setFloat("density", _this.density);
  77319. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77320. });
  77321. return _this;
  77322. }
  77323. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77324. get: function () {
  77325. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77326. return false;
  77327. },
  77328. set: function (useDiffuseColor) {
  77329. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77330. },
  77331. enumerable: true,
  77332. configurable: true
  77333. });
  77334. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77335. return "VolumetricLightScatteringPostProcess";
  77336. };
  77337. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77338. var mesh = subMesh.getMesh();
  77339. // Render this.mesh as default
  77340. if (mesh === this.mesh && mesh.material) {
  77341. return mesh.material.isReady(mesh);
  77342. }
  77343. var defines = [];
  77344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77345. var material = subMesh.getMaterial();
  77346. // Alpha test
  77347. if (material) {
  77348. if (material.needAlphaTesting()) {
  77349. defines.push("#define ALPHATEST");
  77350. }
  77351. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77352. attribs.push(BABYLON.VertexBuffer.UVKind);
  77353. defines.push("#define UV1");
  77354. }
  77355. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77356. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77357. defines.push("#define UV2");
  77358. }
  77359. }
  77360. // Bones
  77361. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77362. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77363. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77364. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77365. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77366. }
  77367. else {
  77368. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77369. }
  77370. // Instances
  77371. if (useInstances) {
  77372. defines.push("#define INSTANCES");
  77373. attribs.push("world0");
  77374. attribs.push("world1");
  77375. attribs.push("world2");
  77376. attribs.push("world3");
  77377. }
  77378. // Get correct effect
  77379. var join = defines.join("\n");
  77380. if (this._cachedDefines !== join) {
  77381. this._cachedDefines = join;
  77382. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77383. }
  77384. return this._volumetricLightScatteringPass.isReady();
  77385. };
  77386. /**
  77387. * Sets the new light position for light scattering effect
  77388. * @param {BABYLON.Vector3} The new custom light position
  77389. */
  77390. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77391. this.customMeshPosition = position;
  77392. };
  77393. /**
  77394. * Returns the light position for light scattering effect
  77395. * @return {BABYLON.Vector3} The custom light position
  77396. */
  77397. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77398. return this.customMeshPosition;
  77399. };
  77400. /**
  77401. * Disposes the internal assets and detaches the post-process from the camera
  77402. */
  77403. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77404. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77405. if (rttIndex !== -1) {
  77406. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77407. }
  77408. this._volumetricLightScatteringRTT.dispose();
  77409. _super.prototype.dispose.call(this, camera);
  77410. };
  77411. /**
  77412. * Returns the render target texture used by the post-process
  77413. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77414. */
  77415. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77416. return this._volumetricLightScatteringRTT;
  77417. };
  77418. // Private methods
  77419. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77420. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77421. return true;
  77422. }
  77423. return false;
  77424. };
  77425. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77426. var _this = this;
  77427. var engine = scene.getEngine();
  77428. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77429. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77430. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77431. this._volumetricLightScatteringRTT.renderList = null;
  77432. this._volumetricLightScatteringRTT.renderParticles = false;
  77433. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77434. var camera = this.getCamera();
  77435. if (camera) {
  77436. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77437. }
  77438. else {
  77439. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77440. }
  77441. // Custom render function for submeshes
  77442. var renderSubMesh = function (subMesh) {
  77443. var mesh = subMesh.getRenderingMesh();
  77444. if (_this._meshExcluded(mesh)) {
  77445. return;
  77446. }
  77447. var material = subMesh.getMaterial();
  77448. if (!material) {
  77449. return;
  77450. }
  77451. var scene = mesh.getScene();
  77452. var engine = scene.getEngine();
  77453. // Culling
  77454. engine.setState(material.backFaceCulling);
  77455. // Managing instances
  77456. var batch = mesh._getInstancesRenderList(subMesh._id);
  77457. if (batch.mustReturn) {
  77458. return;
  77459. }
  77460. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77461. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77462. var effect = _this._volumetricLightScatteringPass;
  77463. if (mesh === _this.mesh) {
  77464. if (subMesh.effect) {
  77465. effect = subMesh.effect;
  77466. }
  77467. else {
  77468. effect = material.getEffect();
  77469. }
  77470. }
  77471. engine.enableEffect(effect);
  77472. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77473. if (mesh === _this.mesh) {
  77474. material.bind(mesh.getWorldMatrix(), mesh);
  77475. }
  77476. else {
  77477. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77478. // Alpha test
  77479. if (material && material.needAlphaTesting()) {
  77480. var alphaTexture = material.getAlphaTestTexture();
  77481. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77482. if (alphaTexture) {
  77483. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77484. }
  77485. }
  77486. // Bones
  77487. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77488. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77489. }
  77490. }
  77491. // Draw
  77492. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77493. }
  77494. };
  77495. // Render target texture callbacks
  77496. var savedSceneClearColor;
  77497. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77498. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77499. savedSceneClearColor = scene.clearColor;
  77500. scene.clearColor = sceneClearColor;
  77501. });
  77502. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77503. scene.clearColor = savedSceneClearColor;
  77504. });
  77505. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77506. var engine = scene.getEngine();
  77507. var index;
  77508. if (depthOnlySubMeshes.length) {
  77509. engine.setColorWrite(false);
  77510. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77511. renderSubMesh(depthOnlySubMeshes.data[index]);
  77512. }
  77513. engine.setColorWrite(true);
  77514. }
  77515. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77516. renderSubMesh(opaqueSubMeshes.data[index]);
  77517. }
  77518. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77519. renderSubMesh(alphaTestSubMeshes.data[index]);
  77520. }
  77521. if (transparentSubMeshes.length) {
  77522. // Sort sub meshes
  77523. for (index = 0; index < transparentSubMeshes.length; index++) {
  77524. var submesh = transparentSubMeshes.data[index];
  77525. var boundingInfo = submesh.getBoundingInfo();
  77526. if (boundingInfo && scene.activeCamera) {
  77527. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77528. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77529. }
  77530. }
  77531. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77532. sortedArray.sort(function (a, b) {
  77533. // Alpha index first
  77534. if (a._alphaIndex > b._alphaIndex) {
  77535. return 1;
  77536. }
  77537. if (a._alphaIndex < b._alphaIndex) {
  77538. return -1;
  77539. }
  77540. // Then distance to camera
  77541. if (a._distanceToCamera < b._distanceToCamera) {
  77542. return 1;
  77543. }
  77544. if (a._distanceToCamera > b._distanceToCamera) {
  77545. return -1;
  77546. }
  77547. return 0;
  77548. });
  77549. // Render sub meshes
  77550. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77551. for (index = 0; index < sortedArray.length; index++) {
  77552. renderSubMesh(sortedArray[index]);
  77553. }
  77554. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77555. }
  77556. };
  77557. };
  77558. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77559. var transform = scene.getTransformMatrix();
  77560. var meshPosition;
  77561. if (this.useCustomMeshPosition) {
  77562. meshPosition = this.customMeshPosition;
  77563. }
  77564. else if (this.attachedNode) {
  77565. meshPosition = this.attachedNode.position;
  77566. }
  77567. else {
  77568. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77569. }
  77570. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77571. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77572. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77573. if (this.invert)
  77574. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77575. };
  77576. // Static methods
  77577. /**
  77578. * Creates a default mesh for the Volumeric Light Scattering post-process
  77579. * @param {string} The mesh name
  77580. * @param {BABYLON.Scene} The scene where to create the mesh
  77581. * @return {BABYLON.Mesh} the default mesh
  77582. */
  77583. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77584. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77585. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77586. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77587. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77588. mesh.material = material;
  77589. return mesh;
  77590. };
  77591. __decorate([
  77592. BABYLON.serializeAsVector3()
  77593. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77594. __decorate([
  77595. BABYLON.serialize()
  77596. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77597. __decorate([
  77598. BABYLON.serialize()
  77599. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77600. __decorate([
  77601. BABYLON.serializeAsMeshReference()
  77602. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77603. __decorate([
  77604. BABYLON.serialize()
  77605. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77606. __decorate([
  77607. BABYLON.serialize()
  77608. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77609. __decorate([
  77610. BABYLON.serialize()
  77611. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77612. __decorate([
  77613. BABYLON.serialize()
  77614. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77615. __decorate([
  77616. BABYLON.serialize()
  77617. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77618. return VolumetricLightScatteringPostProcess;
  77619. }(BABYLON.PostProcess));
  77620. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77621. })(BABYLON || (BABYLON = {}));
  77622. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77623. //
  77624. // This post-process allows the modification of rendered colors by using
  77625. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77626. //
  77627. // The object needs to be provided an url to a texture containing the color
  77628. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77629. // Use an image editing software to tweak the LUT to match your needs.
  77630. //
  77631. // For an example of a color LUT, see here:
  77632. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77633. // For explanations on color grading, see here:
  77634. // http://udn.epicgames.com/Three/ColorGrading.html
  77635. //
  77636. var BABYLON;
  77637. (function (BABYLON) {
  77638. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77639. __extends(ColorCorrectionPostProcess, _super);
  77640. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77641. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77642. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77643. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77644. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77645. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77646. _this.onApply = function (effect) {
  77647. effect.setTexture("colorTable", _this._colorTableTexture);
  77648. };
  77649. return _this;
  77650. }
  77651. return ColorCorrectionPostProcess;
  77652. }(BABYLON.PostProcess));
  77653. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77654. })(BABYLON || (BABYLON = {}));
  77655. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77656. var BABYLON;
  77657. (function (BABYLON) {
  77658. /** Defines operator used for tonemapping */
  77659. var TonemappingOperator;
  77660. (function (TonemappingOperator) {
  77661. /** Hable */
  77662. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77663. /** Reinhard */
  77664. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77665. /** HejiDawson */
  77666. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77667. /** Photographic */
  77668. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77669. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77670. ;
  77671. /**
  77672. * Defines a post process to apply tone mapping
  77673. */
  77674. var TonemapPostProcess = /** @class */ (function (_super) {
  77675. __extends(TonemapPostProcess, _super);
  77676. /**
  77677. * Creates a new TonemapPostProcess
  77678. * @param name defines the name of the postprocess
  77679. * @param _operator defines the operator to use
  77680. * @param exposureAdjustment defines the required exposure adjustement
  77681. * @param camera defines the camera to use (can be null)
  77682. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77683. * @param engine defines the hosting engine (can be ignore if camera is set)
  77684. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77685. */
  77686. function TonemapPostProcess(name, _operator,
  77687. /** Defines the required exposure adjustement */
  77688. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77690. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77691. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77692. _this._operator = _operator;
  77693. _this.exposureAdjustment = exposureAdjustment;
  77694. var defines = "#define ";
  77695. if (_this._operator === TonemappingOperator.Hable)
  77696. defines += "HABLE_TONEMAPPING";
  77697. else if (_this._operator === TonemappingOperator.Reinhard)
  77698. defines += "REINHARD_TONEMAPPING";
  77699. else if (_this._operator === TonemappingOperator.HejiDawson)
  77700. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77701. else if (_this._operator === TonemappingOperator.Photographic)
  77702. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77703. //sadly a second call to create the effect.
  77704. _this.updateEffect(defines);
  77705. _this.onApply = function (effect) {
  77706. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77707. };
  77708. return _this;
  77709. }
  77710. return TonemapPostProcess;
  77711. }(BABYLON.PostProcess));
  77712. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77713. })(BABYLON || (BABYLON = {}));
  77714. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77715. var BABYLON;
  77716. (function (BABYLON) {
  77717. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77718. __extends(DisplayPassPostProcess, _super);
  77719. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77720. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77721. }
  77722. return DisplayPassPostProcess;
  77723. }(BABYLON.PostProcess));
  77724. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77725. })(BABYLON || (BABYLON = {}));
  77726. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77727. var BABYLON;
  77728. (function (BABYLON) {
  77729. var HighlightsPostProcess = /** @class */ (function (_super) {
  77730. __extends(HighlightsPostProcess, _super);
  77731. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77733. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77734. }
  77735. return HighlightsPostProcess;
  77736. }(BABYLON.PostProcess));
  77737. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77738. })(BABYLON || (BABYLON = {}));
  77739. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77740. var BABYLON;
  77741. (function (BABYLON) {
  77742. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77743. __extends(ImageProcessingPostProcess, _super);
  77744. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77745. if (camera === void 0) { camera = null; }
  77746. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77747. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77748. _this._fromLinearSpace = true;
  77749. /**
  77750. * Defines cache preventing GC.
  77751. */
  77752. _this._defines = {
  77753. IMAGEPROCESSING: false,
  77754. VIGNETTE: false,
  77755. VIGNETTEBLENDMODEMULTIPLY: false,
  77756. VIGNETTEBLENDMODEOPAQUE: false,
  77757. TONEMAPPING: false,
  77758. CONTRAST: false,
  77759. COLORCURVES: false,
  77760. COLORGRADING: false,
  77761. COLORGRADING3D: false,
  77762. FROMLINEARSPACE: false,
  77763. SAMPLER3DGREENDEPTH: false,
  77764. SAMPLER3DBGRMAP: false,
  77765. IMAGEPROCESSINGPOSTPROCESS: false,
  77766. EXPOSURE: false,
  77767. };
  77768. // Setup the configuration as forced by the constructor. This would then not force the
  77769. // scene materials output in linear space and let untouched the default forward pass.
  77770. if (imageProcessingConfiguration) {
  77771. imageProcessingConfiguration.applyByPostProcess = true;
  77772. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77773. // This will cause the shader to be compiled
  77774. _this.fromLinearSpace = false;
  77775. }
  77776. // Setup the default processing configuration to the scene.
  77777. else {
  77778. _this._attachImageProcessingConfiguration(null, true);
  77779. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77780. }
  77781. _this.onApply = function (effect) {
  77782. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77783. };
  77784. return _this;
  77785. }
  77786. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77787. /**
  77788. * Gets the image processing configuration used either in this material.
  77789. */
  77790. get: function () {
  77791. return this._imageProcessingConfiguration;
  77792. },
  77793. /**
  77794. * Sets the Default image processing configuration used either in the this material.
  77795. *
  77796. * If sets to null, the scene one is in use.
  77797. */
  77798. set: function (value) {
  77799. this._attachImageProcessingConfiguration(value);
  77800. },
  77801. enumerable: true,
  77802. configurable: true
  77803. });
  77804. /**
  77805. * Attaches a new image processing configuration to the PBR Material.
  77806. * @param configuration
  77807. */
  77808. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77809. var _this = this;
  77810. if (doNotBuild === void 0) { doNotBuild = false; }
  77811. if (configuration === this._imageProcessingConfiguration) {
  77812. return;
  77813. }
  77814. // Detaches observer.
  77815. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77816. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77817. }
  77818. // Pick the scene configuration if needed.
  77819. if (!configuration) {
  77820. var scene = null;
  77821. var engine = this.getEngine();
  77822. var camera = this.getCamera();
  77823. if (camera) {
  77824. scene = camera.getScene();
  77825. }
  77826. else if (engine && engine.scenes) {
  77827. var scenes = engine.scenes;
  77828. scene = scenes[scenes.length - 1];
  77829. }
  77830. else {
  77831. scene = BABYLON.Engine.LastCreatedScene;
  77832. }
  77833. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77834. }
  77835. else {
  77836. this._imageProcessingConfiguration = configuration;
  77837. }
  77838. // Attaches observer.
  77839. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77840. _this._updateParameters();
  77841. });
  77842. // Ensure the effect will be rebuilt.
  77843. if (!doNotBuild) {
  77844. this._updateParameters();
  77845. }
  77846. };
  77847. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77848. /**
  77849. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77850. */
  77851. get: function () {
  77852. return this.imageProcessingConfiguration.colorCurves;
  77853. },
  77854. /**
  77855. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77856. */
  77857. set: function (value) {
  77858. this.imageProcessingConfiguration.colorCurves = value;
  77859. },
  77860. enumerable: true,
  77861. configurable: true
  77862. });
  77863. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77864. /**
  77865. * Gets wether the color curves effect is enabled.
  77866. */
  77867. get: function () {
  77868. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77869. },
  77870. /**
  77871. * Sets wether the color curves effect is enabled.
  77872. */
  77873. set: function (value) {
  77874. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77880. /**
  77881. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77882. */
  77883. get: function () {
  77884. return this.imageProcessingConfiguration.colorGradingTexture;
  77885. },
  77886. /**
  77887. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77888. */
  77889. set: function (value) {
  77890. this.imageProcessingConfiguration.colorGradingTexture = value;
  77891. },
  77892. enumerable: true,
  77893. configurable: true
  77894. });
  77895. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77896. /**
  77897. * Gets wether the color grading effect is enabled.
  77898. */
  77899. get: function () {
  77900. return this.imageProcessingConfiguration.colorGradingEnabled;
  77901. },
  77902. /**
  77903. * Gets wether the color grading effect is enabled.
  77904. */
  77905. set: function (value) {
  77906. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77907. },
  77908. enumerable: true,
  77909. configurable: true
  77910. });
  77911. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77912. /**
  77913. * Gets exposure used in the effect.
  77914. */
  77915. get: function () {
  77916. return this.imageProcessingConfiguration.exposure;
  77917. },
  77918. /**
  77919. * Sets exposure used in the effect.
  77920. */
  77921. set: function (value) {
  77922. this.imageProcessingConfiguration.exposure = value;
  77923. },
  77924. enumerable: true,
  77925. configurable: true
  77926. });
  77927. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77928. /**
  77929. * Gets wether tonemapping is enabled or not.
  77930. */
  77931. get: function () {
  77932. return this._imageProcessingConfiguration.toneMappingEnabled;
  77933. },
  77934. /**
  77935. * Sets wether tonemapping is enabled or not
  77936. */
  77937. set: function (value) {
  77938. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. ;
  77944. ;
  77945. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77946. /**
  77947. * Gets contrast used in the effect.
  77948. */
  77949. get: function () {
  77950. return this.imageProcessingConfiguration.contrast;
  77951. },
  77952. /**
  77953. * Sets contrast used in the effect.
  77954. */
  77955. set: function (value) {
  77956. this.imageProcessingConfiguration.contrast = value;
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77962. /**
  77963. * Gets Vignette stretch size.
  77964. */
  77965. get: function () {
  77966. return this.imageProcessingConfiguration.vignetteStretch;
  77967. },
  77968. /**
  77969. * Sets Vignette stretch size.
  77970. */
  77971. set: function (value) {
  77972. this.imageProcessingConfiguration.vignetteStretch = value;
  77973. },
  77974. enumerable: true,
  77975. configurable: true
  77976. });
  77977. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77978. /**
  77979. * Gets Vignette centre X Offset.
  77980. */
  77981. get: function () {
  77982. return this.imageProcessingConfiguration.vignetteCentreX;
  77983. },
  77984. /**
  77985. * Sets Vignette centre X Offset.
  77986. */
  77987. set: function (value) {
  77988. this.imageProcessingConfiguration.vignetteCentreX = value;
  77989. },
  77990. enumerable: true,
  77991. configurable: true
  77992. });
  77993. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77994. /**
  77995. * Gets Vignette centre Y Offset.
  77996. */
  77997. get: function () {
  77998. return this.imageProcessingConfiguration.vignetteCentreY;
  77999. },
  78000. /**
  78001. * Sets Vignette centre Y Offset.
  78002. */
  78003. set: function (value) {
  78004. this.imageProcessingConfiguration.vignetteCentreY = value;
  78005. },
  78006. enumerable: true,
  78007. configurable: true
  78008. });
  78009. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78010. /**
  78011. * Gets Vignette weight or intensity of the vignette effect.
  78012. */
  78013. get: function () {
  78014. return this.imageProcessingConfiguration.vignetteWeight;
  78015. },
  78016. /**
  78017. * Sets Vignette weight or intensity of the vignette effect.
  78018. */
  78019. set: function (value) {
  78020. this.imageProcessingConfiguration.vignetteWeight = value;
  78021. },
  78022. enumerable: true,
  78023. configurable: true
  78024. });
  78025. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78026. /**
  78027. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78028. * if vignetteEnabled is set to true.
  78029. */
  78030. get: function () {
  78031. return this.imageProcessingConfiguration.vignetteColor;
  78032. },
  78033. /**
  78034. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78035. * if vignetteEnabled is set to true.
  78036. */
  78037. set: function (value) {
  78038. this.imageProcessingConfiguration.vignetteColor = value;
  78039. },
  78040. enumerable: true,
  78041. configurable: true
  78042. });
  78043. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78044. /**
  78045. * Gets Camera field of view used by the Vignette effect.
  78046. */
  78047. get: function () {
  78048. return this.imageProcessingConfiguration.vignetteCameraFov;
  78049. },
  78050. /**
  78051. * Sets Camera field of view used by the Vignette effect.
  78052. */
  78053. set: function (value) {
  78054. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78055. },
  78056. enumerable: true,
  78057. configurable: true
  78058. });
  78059. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78060. /**
  78061. * Gets the vignette blend mode allowing different kind of effect.
  78062. */
  78063. get: function () {
  78064. return this.imageProcessingConfiguration.vignetteBlendMode;
  78065. },
  78066. /**
  78067. * Sets the vignette blend mode allowing different kind of effect.
  78068. */
  78069. set: function (value) {
  78070. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78071. },
  78072. enumerable: true,
  78073. configurable: true
  78074. });
  78075. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78076. /**
  78077. * Gets wether the vignette effect is enabled.
  78078. */
  78079. get: function () {
  78080. return this.imageProcessingConfiguration.vignetteEnabled;
  78081. },
  78082. /**
  78083. * Sets wether the vignette effect is enabled.
  78084. */
  78085. set: function (value) {
  78086. this.imageProcessingConfiguration.vignetteEnabled = value;
  78087. },
  78088. enumerable: true,
  78089. configurable: true
  78090. });
  78091. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78092. /**
  78093. * Gets wether the input of the processing is in Gamma or Linear Space.
  78094. */
  78095. get: function () {
  78096. return this._fromLinearSpace;
  78097. },
  78098. /**
  78099. * Sets wether the input of the processing is in Gamma or Linear Space.
  78100. */
  78101. set: function (value) {
  78102. if (this._fromLinearSpace === value) {
  78103. return;
  78104. }
  78105. this._fromLinearSpace = value;
  78106. this._updateParameters();
  78107. },
  78108. enumerable: true,
  78109. configurable: true
  78110. });
  78111. ImageProcessingPostProcess.prototype.getClassName = function () {
  78112. return "ImageProcessingPostProcess";
  78113. };
  78114. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78115. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78116. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78117. var defines = "";
  78118. for (var define in this._defines) {
  78119. if (this._defines[define]) {
  78120. defines += "#define " + define + ";\r\n";
  78121. }
  78122. }
  78123. var samplers = ["textureSampler"];
  78124. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78125. var uniforms = ["scale"];
  78126. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78127. this.updateEffect(defines, uniforms, samplers);
  78128. };
  78129. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78130. _super.prototype.dispose.call(this, camera);
  78131. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78132. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78133. }
  78134. this.imageProcessingConfiguration.applyByPostProcess = false;
  78135. };
  78136. __decorate([
  78137. BABYLON.serialize()
  78138. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78139. return ImageProcessingPostProcess;
  78140. }(BABYLON.PostProcess));
  78141. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78142. })(BABYLON || (BABYLON = {}));
  78143. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78144. var BABYLON;
  78145. (function (BABYLON) {
  78146. /**
  78147. * Class used to store bone information
  78148. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78149. */
  78150. var Bone = /** @class */ (function (_super) {
  78151. __extends(Bone, _super);
  78152. /**
  78153. * Create a new bone
  78154. * @param name defines the bone name
  78155. * @param skeleton defines the parent skeleton
  78156. * @param parentBone defines the parent (can be null if the bone is the root)
  78157. * @param localMatrix defines the local matrix
  78158. * @param restPose defines the rest pose matrix
  78159. * @param baseMatrix defines the base matrix
  78160. * @param index defines index of the bone in the hiearchy
  78161. */
  78162. function Bone(
  78163. /**
  78164. * defines the bone name
  78165. */
  78166. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78167. if (parentBone === void 0) { parentBone = null; }
  78168. if (localMatrix === void 0) { localMatrix = null; }
  78169. if (restPose === void 0) { restPose = null; }
  78170. if (baseMatrix === void 0) { baseMatrix = null; }
  78171. if (index === void 0) { index = null; }
  78172. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78173. _this.name = name;
  78174. /**
  78175. * Gets the list of child bones
  78176. */
  78177. _this.children = new Array();
  78178. /** Gets the animations associated with this bone */
  78179. _this.animations = new Array();
  78180. /**
  78181. * @hidden Internal only
  78182. * Set this value to map this bone to a different index in the transform matrices
  78183. * Set this value to -1 to exclude the bone from the transform matrices
  78184. */
  78185. _this._index = null;
  78186. _this._absoluteTransform = new BABYLON.Matrix();
  78187. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78188. _this._scalingDeterminant = 1;
  78189. _this._worldTransform = new BABYLON.Matrix();
  78190. _this._needToDecompose = true;
  78191. _this._needToCompose = false;
  78192. _this._skeleton = skeleton;
  78193. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78194. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78195. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78196. _this._index = index;
  78197. skeleton.bones.push(_this);
  78198. _this.setParent(parentBone, false);
  78199. if (baseMatrix || localMatrix) {
  78200. _this._updateDifferenceMatrix();
  78201. }
  78202. return _this;
  78203. }
  78204. Object.defineProperty(Bone.prototype, "_matrix", {
  78205. /** @hidden */
  78206. get: function () {
  78207. this._compose();
  78208. return this._localMatrix;
  78209. },
  78210. /** @hidden */
  78211. set: function (value) {
  78212. this._localMatrix.copyFrom(value);
  78213. this._needToDecompose = true;
  78214. },
  78215. enumerable: true,
  78216. configurable: true
  78217. });
  78218. // Members
  78219. /**
  78220. * Gets the parent skeleton
  78221. * @returns a skeleton
  78222. */
  78223. Bone.prototype.getSkeleton = function () {
  78224. return this._skeleton;
  78225. };
  78226. /**
  78227. * Gets parent bone
  78228. * @returns a bone or null if the bone is the root of the bone hierarchy
  78229. */
  78230. Bone.prototype.getParent = function () {
  78231. return this._parent;
  78232. };
  78233. /**
  78234. * Sets the parent bone
  78235. * @param parent defines the parent (can be null if the bone is the root)
  78236. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78237. */
  78238. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78239. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78240. if (this._parent === parent) {
  78241. return;
  78242. }
  78243. if (this._parent) {
  78244. var index = this._parent.children.indexOf(this);
  78245. if (index !== -1) {
  78246. this._parent.children.splice(index, 1);
  78247. }
  78248. }
  78249. this._parent = parent;
  78250. if (this._parent) {
  78251. this._parent.children.push(this);
  78252. }
  78253. if (updateDifferenceMatrix) {
  78254. this._updateDifferenceMatrix();
  78255. }
  78256. this.markAsDirty();
  78257. };
  78258. /**
  78259. * Gets the local matrix
  78260. * @returns a matrix
  78261. */
  78262. Bone.prototype.getLocalMatrix = function () {
  78263. this._compose();
  78264. return this._localMatrix;
  78265. };
  78266. /**
  78267. * Gets the base matrix (initial matrix which remains unchanged)
  78268. * @returns a matrix
  78269. */
  78270. Bone.prototype.getBaseMatrix = function () {
  78271. return this._baseMatrix;
  78272. };
  78273. /**
  78274. * Gets the rest pose matrix
  78275. * @returns a matrix
  78276. */
  78277. Bone.prototype.getRestPose = function () {
  78278. return this._restPose;
  78279. };
  78280. /**
  78281. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78282. */
  78283. Bone.prototype.getWorldMatrix = function () {
  78284. return this._worldTransform;
  78285. };
  78286. /**
  78287. * Sets the local matrix to rest pose matrix
  78288. */
  78289. Bone.prototype.returnToRest = function () {
  78290. this.updateMatrix(this._restPose.clone());
  78291. };
  78292. /**
  78293. * Gets the inverse of the absolute transform matrix.
  78294. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78295. * @returns a matrix
  78296. */
  78297. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78298. return this._invertedAbsoluteTransform;
  78299. };
  78300. /**
  78301. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78302. * @returns a matrix
  78303. */
  78304. Bone.prototype.getAbsoluteTransform = function () {
  78305. return this._absoluteTransform;
  78306. };
  78307. Object.defineProperty(Bone.prototype, "position", {
  78308. // Properties (matches AbstractMesh properties)
  78309. /** Gets or sets current position (in local space) */
  78310. get: function () {
  78311. this._decompose();
  78312. return this._localPosition;
  78313. },
  78314. set: function (newPosition) {
  78315. this._decompose();
  78316. this._localPosition.copyFrom(newPosition);
  78317. this._markAsDirtyAndCompose();
  78318. },
  78319. enumerable: true,
  78320. configurable: true
  78321. });
  78322. Object.defineProperty(Bone.prototype, "rotation", {
  78323. /** Gets or sets current rotation (in local space) */
  78324. get: function () {
  78325. return this.getRotation();
  78326. },
  78327. set: function (newRotation) {
  78328. this.setRotation(newRotation);
  78329. },
  78330. enumerable: true,
  78331. configurable: true
  78332. });
  78333. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78334. /** Gets or sets current rotation quaternion (in local space) */
  78335. get: function () {
  78336. this._decompose();
  78337. return this._localRotation;
  78338. },
  78339. set: function (newRotation) {
  78340. this.setRotationQuaternion(newRotation);
  78341. },
  78342. enumerable: true,
  78343. configurable: true
  78344. });
  78345. Object.defineProperty(Bone.prototype, "scaling", {
  78346. /** Gets or sets current scaling (in local space) */
  78347. get: function () {
  78348. return this.getScale();
  78349. },
  78350. set: function (newScaling) {
  78351. this.setScale(newScaling);
  78352. },
  78353. enumerable: true,
  78354. configurable: true
  78355. });
  78356. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78357. /**
  78358. * Gets the animation properties override
  78359. */
  78360. get: function () {
  78361. return this._skeleton.animationPropertiesOverride;
  78362. },
  78363. enumerable: true,
  78364. configurable: true
  78365. });
  78366. // Methods
  78367. Bone.prototype._decompose = function () {
  78368. if (!this._needToDecompose) {
  78369. return;
  78370. }
  78371. this._needToDecompose = false;
  78372. if (!this._localScaling) {
  78373. this._localScaling = BABYLON.Vector3.Zero();
  78374. this._localRotation = BABYLON.Quaternion.Zero();
  78375. this._localPosition = BABYLON.Vector3.Zero();
  78376. }
  78377. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78378. };
  78379. Bone.prototype._compose = function () {
  78380. if (!this._needToCompose) {
  78381. return;
  78382. }
  78383. this._needToCompose = false;
  78384. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78385. };
  78386. /**
  78387. * Update the base and local matrices
  78388. * @param matrix defines the new base or local matrix
  78389. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78390. * @param updateLocalMatrix defines if the local matrix should be updated
  78391. */
  78392. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78393. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78394. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78395. this._baseMatrix.copyFrom(matrix);
  78396. if (updateDifferenceMatrix) {
  78397. this._updateDifferenceMatrix();
  78398. }
  78399. if (updateLocalMatrix) {
  78400. this._localMatrix.copyFrom(matrix);
  78401. this._markAsDirtyAndDecompose();
  78402. }
  78403. else {
  78404. this.markAsDirty();
  78405. }
  78406. };
  78407. /** @hidden */
  78408. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78409. if (updateChildren === void 0) { updateChildren = true; }
  78410. if (!rootMatrix) {
  78411. rootMatrix = this._baseMatrix;
  78412. }
  78413. if (this._parent) {
  78414. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78415. }
  78416. else {
  78417. this._absoluteTransform.copyFrom(rootMatrix);
  78418. }
  78419. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78420. if (updateChildren) {
  78421. for (var index = 0; index < this.children.length; index++) {
  78422. this.children[index]._updateDifferenceMatrix();
  78423. }
  78424. }
  78425. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78426. };
  78427. /**
  78428. * Flag the bone as dirty (Forcing it to update everything)
  78429. */
  78430. Bone.prototype.markAsDirty = function () {
  78431. this._currentRenderId++;
  78432. this._childRenderId++;
  78433. this._skeleton._markAsDirty();
  78434. };
  78435. Bone.prototype._markAsDirtyAndCompose = function () {
  78436. this.markAsDirty();
  78437. this._needToCompose = true;
  78438. };
  78439. Bone.prototype._markAsDirtyAndDecompose = function () {
  78440. this.markAsDirty();
  78441. this._needToDecompose = true;
  78442. };
  78443. /**
  78444. * Copy an animation range from another bone
  78445. * @param source defines the source bone
  78446. * @param rangeName defines the range name to copy
  78447. * @param frameOffset defines the frame offset
  78448. * @param rescaleAsRequired defines if rescaling must be applied if required
  78449. * @param skelDimensionsRatio defines the scaling ratio
  78450. * @returns true if operation was successful
  78451. */
  78452. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78453. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78454. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78455. // all animation may be coming from a library skeleton, so may need to create animation
  78456. if (this.animations.length === 0) {
  78457. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78458. this.animations[0].setKeys([]);
  78459. }
  78460. // get animation info / verify there is such a range from the source bone
  78461. var sourceRange = source.animations[0].getRange(rangeName);
  78462. if (!sourceRange) {
  78463. return false;
  78464. }
  78465. var from = sourceRange.from;
  78466. var to = sourceRange.to;
  78467. var sourceKeys = source.animations[0].getKeys();
  78468. // rescaling prep
  78469. var sourceBoneLength = source.length;
  78470. var sourceParent = source.getParent();
  78471. var parent = this.getParent();
  78472. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78473. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78474. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78475. var destKeys = this.animations[0].getKeys();
  78476. // loop vars declaration
  78477. var orig;
  78478. var origTranslation;
  78479. var mat;
  78480. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78481. orig = sourceKeys[key];
  78482. if (orig.frame >= from && orig.frame <= to) {
  78483. if (rescaleAsRequired) {
  78484. mat = orig.value.clone();
  78485. // scale based on parent ratio, when bone has parent
  78486. if (parentScalingReqd) {
  78487. origTranslation = mat.getTranslation();
  78488. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78489. // scale based on skeleton dimension ratio when root bone, and value is passed
  78490. }
  78491. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78492. origTranslation = mat.getTranslation();
  78493. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78494. // use original when root bone, and no data for skelDimensionsRatio
  78495. }
  78496. else {
  78497. mat = orig.value;
  78498. }
  78499. }
  78500. else {
  78501. mat = orig.value;
  78502. }
  78503. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78504. }
  78505. }
  78506. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78507. return true;
  78508. };
  78509. /**
  78510. * Translate the bone in local or world space
  78511. * @param vec The amount to translate the bone
  78512. * @param space The space that the translation is in
  78513. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78514. */
  78515. Bone.prototype.translate = function (vec, space, mesh) {
  78516. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78517. var lm = this.getLocalMatrix();
  78518. if (space == BABYLON.Space.LOCAL) {
  78519. lm.m[12] += vec.x;
  78520. lm.m[13] += vec.y;
  78521. lm.m[14] += vec.z;
  78522. }
  78523. else {
  78524. var wm = null;
  78525. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78526. if (mesh) {
  78527. wm = mesh.getWorldMatrix();
  78528. }
  78529. this._skeleton.computeAbsoluteTransforms();
  78530. var tmat = Bone._tmpMats[0];
  78531. var tvec = Bone._tmpVecs[0];
  78532. if (this._parent) {
  78533. if (mesh && wm) {
  78534. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78535. tmat.multiplyToRef(wm, tmat);
  78536. }
  78537. else {
  78538. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78539. }
  78540. }
  78541. tmat.m[12] = 0;
  78542. tmat.m[13] = 0;
  78543. tmat.m[14] = 0;
  78544. tmat.invert();
  78545. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78546. lm.m[12] += tvec.x;
  78547. lm.m[13] += tvec.y;
  78548. lm.m[14] += tvec.z;
  78549. }
  78550. this._markAsDirtyAndDecompose();
  78551. };
  78552. /**
  78553. * Set the postion of the bone in local or world space
  78554. * @param position The position to set the bone
  78555. * @param space The space that the position is in
  78556. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78557. */
  78558. Bone.prototype.setPosition = function (position, space, mesh) {
  78559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78560. var lm = this.getLocalMatrix();
  78561. if (space == BABYLON.Space.LOCAL) {
  78562. lm.m[12] = position.x;
  78563. lm.m[13] = position.y;
  78564. lm.m[14] = position.z;
  78565. }
  78566. else {
  78567. var wm = null;
  78568. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78569. if (mesh) {
  78570. wm = mesh.getWorldMatrix();
  78571. }
  78572. this._skeleton.computeAbsoluteTransforms();
  78573. var tmat = Bone._tmpMats[0];
  78574. var vec = Bone._tmpVecs[0];
  78575. if (this._parent) {
  78576. if (mesh && wm) {
  78577. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78578. tmat.multiplyToRef(wm, tmat);
  78579. }
  78580. else {
  78581. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78582. }
  78583. }
  78584. tmat.invert();
  78585. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78586. lm.m[12] = vec.x;
  78587. lm.m[13] = vec.y;
  78588. lm.m[14] = vec.z;
  78589. }
  78590. this._markAsDirtyAndDecompose();
  78591. };
  78592. /**
  78593. * Set the absolute position of the bone (world space)
  78594. * @param position The position to set the bone
  78595. * @param mesh The mesh that this bone is attached to
  78596. */
  78597. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78598. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78599. };
  78600. /**
  78601. * Scale the bone on the x, y and z axes (in local space)
  78602. * @param x The amount to scale the bone on the x axis
  78603. * @param y The amount to scale the bone on the y axis
  78604. * @param z The amount to scale the bone on the z axis
  78605. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78606. */
  78607. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78608. if (scaleChildren === void 0) { scaleChildren = false; }
  78609. var locMat = this.getLocalMatrix();
  78610. // Apply new scaling on top of current local matrix
  78611. var scaleMat = Bone._tmpMats[0];
  78612. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78613. scaleMat.multiplyToRef(locMat, locMat);
  78614. // Invert scaling matrix and apply the inverse to all children
  78615. scaleMat.invert();
  78616. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78617. var child = _a[_i];
  78618. var cm = child.getLocalMatrix();
  78619. cm.multiplyToRef(scaleMat, cm);
  78620. cm.m[12] *= x;
  78621. cm.m[13] *= y;
  78622. cm.m[14] *= z;
  78623. child._markAsDirtyAndDecompose();
  78624. }
  78625. this._markAsDirtyAndDecompose();
  78626. if (scaleChildren) {
  78627. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78628. var child = _c[_b];
  78629. child.scale(x, y, z, scaleChildren);
  78630. }
  78631. }
  78632. };
  78633. /**
  78634. * Set the bone scaling in local space
  78635. * @param scale defines the scaling vector
  78636. */
  78637. Bone.prototype.setScale = function (scale) {
  78638. this._decompose();
  78639. this._localScaling.copyFrom(scale);
  78640. this._markAsDirtyAndCompose();
  78641. };
  78642. /**
  78643. * Gets the current scaling in local space
  78644. * @returns the current scaling vector
  78645. */
  78646. Bone.prototype.getScale = function () {
  78647. this._decompose();
  78648. return this._localScaling;
  78649. };
  78650. /**
  78651. * Gets the current scaling in local space and stores it in a target vector
  78652. * @param result defines the target vector
  78653. */
  78654. Bone.prototype.getScaleToRef = function (result) {
  78655. this._decompose();
  78656. result.copyFrom(this._localScaling);
  78657. };
  78658. /**
  78659. * Set the yaw, pitch, and roll of the bone in local or world space
  78660. * @param yaw The rotation of the bone on the y axis
  78661. * @param pitch The rotation of the bone on the x axis
  78662. * @param roll The rotation of the bone on the z axis
  78663. * @param space The space that the axes of rotation are in
  78664. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78665. */
  78666. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78667. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78668. if (space === BABYLON.Space.LOCAL) {
  78669. var quat = Bone._tmpQuat;
  78670. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78671. this.setRotationQuaternion(quat, space, mesh);
  78672. return;
  78673. }
  78674. var rotMatInv = Bone._tmpMats[0];
  78675. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78676. return;
  78677. }
  78678. var rotMat = Bone._tmpMats[1];
  78679. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78680. rotMatInv.multiplyToRef(rotMat, rotMat);
  78681. this._rotateWithMatrix(rotMat, space, mesh);
  78682. };
  78683. /**
  78684. * Add a rotation to the bone on an axis in local or world space
  78685. * @param axis The axis to rotate the bone on
  78686. * @param amount The amount to rotate the bone
  78687. * @param space The space that the axis is in
  78688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78689. */
  78690. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78692. var rmat = Bone._tmpMats[0];
  78693. rmat.m[12] = 0;
  78694. rmat.m[13] = 0;
  78695. rmat.m[14] = 0;
  78696. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78697. this._rotateWithMatrix(rmat, space, mesh);
  78698. };
  78699. /**
  78700. * Set the rotation of the bone to a particular axis angle in local or world space
  78701. * @param axis The axis to rotate the bone on
  78702. * @param angle The angle that the bone should be rotated to
  78703. * @param space The space that the axis is in
  78704. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78705. */
  78706. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78708. if (space === BABYLON.Space.LOCAL) {
  78709. var quat = Bone._tmpQuat;
  78710. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78711. this.setRotationQuaternion(quat, space, mesh);
  78712. return;
  78713. }
  78714. var rotMatInv = Bone._tmpMats[0];
  78715. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78716. return;
  78717. }
  78718. var rotMat = Bone._tmpMats[1];
  78719. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78720. rotMatInv.multiplyToRef(rotMat, rotMat);
  78721. this._rotateWithMatrix(rotMat, space, mesh);
  78722. };
  78723. /**
  78724. * Set the euler rotation of the bone in local of world space
  78725. * @param rotation The euler rotation that the bone should be set to
  78726. * @param space The space that the rotation is in
  78727. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78728. */
  78729. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78731. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78732. };
  78733. /**
  78734. * Set the quaternion rotation of the bone in local of world space
  78735. * @param quat The quaternion rotation that the bone should be set to
  78736. * @param space The space that the rotation is in
  78737. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78738. */
  78739. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78741. if (space === BABYLON.Space.LOCAL) {
  78742. this._decompose();
  78743. this._localRotation.copyFrom(quat);
  78744. this._markAsDirtyAndCompose();
  78745. return;
  78746. }
  78747. var rotMatInv = Bone._tmpMats[0];
  78748. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78749. return;
  78750. }
  78751. var rotMat = Bone._tmpMats[1];
  78752. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78753. rotMatInv.multiplyToRef(rotMat, rotMat);
  78754. this._rotateWithMatrix(rotMat, space, mesh);
  78755. };
  78756. /**
  78757. * Set the rotation matrix of the bone in local of world space
  78758. * @param rotMat The rotation matrix that the bone should be set to
  78759. * @param space The space that the rotation is in
  78760. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78761. */
  78762. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78764. if (space === BABYLON.Space.LOCAL) {
  78765. var quat = Bone._tmpQuat;
  78766. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78767. this.setRotationQuaternion(quat, space, mesh);
  78768. return;
  78769. }
  78770. var rotMatInv = Bone._tmpMats[0];
  78771. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78772. return;
  78773. }
  78774. var rotMat2 = Bone._tmpMats[1];
  78775. rotMat2.copyFrom(rotMat);
  78776. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78777. this._rotateWithMatrix(rotMat2, space, mesh);
  78778. };
  78779. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78781. var lmat = this.getLocalMatrix();
  78782. var lx = lmat.m[12];
  78783. var ly = lmat.m[13];
  78784. var lz = lmat.m[14];
  78785. var parent = this.getParent();
  78786. var parentScale = Bone._tmpMats[3];
  78787. var parentScaleInv = Bone._tmpMats[4];
  78788. if (parent && space == BABYLON.Space.WORLD) {
  78789. if (mesh) {
  78790. parentScale.copyFrom(mesh.getWorldMatrix());
  78791. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78792. }
  78793. else {
  78794. parentScale.copyFrom(parent.getAbsoluteTransform());
  78795. }
  78796. parentScaleInv.copyFrom(parentScale);
  78797. parentScaleInv.invert();
  78798. lmat.multiplyToRef(parentScale, lmat);
  78799. lmat.multiplyToRef(rmat, lmat);
  78800. lmat.multiplyToRef(parentScaleInv, lmat);
  78801. }
  78802. else {
  78803. if (space == BABYLON.Space.WORLD && mesh) {
  78804. parentScale.copyFrom(mesh.getWorldMatrix());
  78805. parentScaleInv.copyFrom(parentScale);
  78806. parentScaleInv.invert();
  78807. lmat.multiplyToRef(parentScale, lmat);
  78808. lmat.multiplyToRef(rmat, lmat);
  78809. lmat.multiplyToRef(parentScaleInv, lmat);
  78810. }
  78811. else {
  78812. lmat.multiplyToRef(rmat, lmat);
  78813. }
  78814. }
  78815. lmat.m[12] = lx;
  78816. lmat.m[13] = ly;
  78817. lmat.m[14] = lz;
  78818. this.computeAbsoluteTransforms();
  78819. this._markAsDirtyAndDecompose();
  78820. };
  78821. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78822. var scaleMatrix = Bone._tmpMats[2];
  78823. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78824. if (mesh) {
  78825. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78826. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78827. }
  78828. rotMatInv.invert();
  78829. if (isNaN(rotMatInv.m[0])) {
  78830. // Matrix failed to invert.
  78831. // This can happen if scale is zero for example.
  78832. return false;
  78833. }
  78834. scaleMatrix.m[0] *= this._scalingDeterminant;
  78835. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78836. return true;
  78837. };
  78838. /**
  78839. * Get the position of the bone in local or world space
  78840. * @param space The space that the returned position is in
  78841. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78842. * @returns The position of the bone
  78843. */
  78844. Bone.prototype.getPosition = function (space, mesh) {
  78845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78846. if (mesh === void 0) { mesh = null; }
  78847. var pos = BABYLON.Vector3.Zero();
  78848. this.getPositionToRef(space, mesh, pos);
  78849. return pos;
  78850. };
  78851. /**
  78852. * Copy the position of the bone to a vector3 in local or world space
  78853. * @param space The space that the returned position is in
  78854. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78855. * @param result The vector3 to copy the position to
  78856. */
  78857. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78859. if (space == BABYLON.Space.LOCAL) {
  78860. var lm = this.getLocalMatrix();
  78861. result.x = lm.m[12];
  78862. result.y = lm.m[13];
  78863. result.z = lm.m[14];
  78864. }
  78865. else {
  78866. var wm = null;
  78867. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78868. if (mesh) {
  78869. wm = mesh.getWorldMatrix();
  78870. }
  78871. this._skeleton.computeAbsoluteTransforms();
  78872. var tmat = Bone._tmpMats[0];
  78873. if (mesh && wm) {
  78874. tmat.copyFrom(this.getAbsoluteTransform());
  78875. tmat.multiplyToRef(wm, tmat);
  78876. }
  78877. else {
  78878. tmat = this.getAbsoluteTransform();
  78879. }
  78880. result.x = tmat.m[12];
  78881. result.y = tmat.m[13];
  78882. result.z = tmat.m[14];
  78883. }
  78884. };
  78885. /**
  78886. * Get the absolute position of the bone (world space)
  78887. * @param mesh The mesh that this bone is attached to
  78888. * @returns The absolute position of the bone
  78889. */
  78890. Bone.prototype.getAbsolutePosition = function (mesh) {
  78891. if (mesh === void 0) { mesh = null; }
  78892. var pos = BABYLON.Vector3.Zero();
  78893. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78894. return pos;
  78895. };
  78896. /**
  78897. * Copy the absolute position of the bone (world space) to the result param
  78898. * @param mesh The mesh that this bone is attached to
  78899. * @param result The vector3 to copy the absolute position to
  78900. */
  78901. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78902. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78903. };
  78904. /**
  78905. * Compute the absolute transforms of this bone and its children
  78906. */
  78907. Bone.prototype.computeAbsoluteTransforms = function () {
  78908. this._compose();
  78909. if (this._parent) {
  78910. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78911. }
  78912. else {
  78913. this._absoluteTransform.copyFrom(this._localMatrix);
  78914. var poseMatrix = this._skeleton.getPoseMatrix();
  78915. if (poseMatrix) {
  78916. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78917. }
  78918. }
  78919. var children = this.children;
  78920. var len = children.length;
  78921. for (var i = 0; i < len; i++) {
  78922. children[i].computeAbsoluteTransforms();
  78923. }
  78924. };
  78925. /**
  78926. * Get the world direction from an axis that is in the local space of the bone
  78927. * @param localAxis The local direction that is used to compute the world direction
  78928. * @param mesh The mesh that this bone is attached to
  78929. * @returns The world direction
  78930. */
  78931. Bone.prototype.getDirection = function (localAxis, mesh) {
  78932. if (mesh === void 0) { mesh = null; }
  78933. var result = BABYLON.Vector3.Zero();
  78934. this.getDirectionToRef(localAxis, mesh, result);
  78935. return result;
  78936. };
  78937. /**
  78938. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78939. * @param localAxis The local direction that is used to compute the world direction
  78940. * @param mesh The mesh that this bone is attached to
  78941. * @param result The vector3 that the world direction will be copied to
  78942. */
  78943. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78944. if (mesh === void 0) { mesh = null; }
  78945. var wm = null;
  78946. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78947. if (mesh) {
  78948. wm = mesh.getWorldMatrix();
  78949. }
  78950. this._skeleton.computeAbsoluteTransforms();
  78951. var mat = Bone._tmpMats[0];
  78952. mat.copyFrom(this.getAbsoluteTransform());
  78953. if (mesh && wm) {
  78954. mat.multiplyToRef(wm, mat);
  78955. }
  78956. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78957. result.normalize();
  78958. };
  78959. /**
  78960. * Get the euler rotation of the bone in local or world space
  78961. * @param space The space that the rotation should be in
  78962. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78963. * @returns The euler rotation
  78964. */
  78965. Bone.prototype.getRotation = function (space, mesh) {
  78966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78967. if (mesh === void 0) { mesh = null; }
  78968. var result = BABYLON.Vector3.Zero();
  78969. this.getRotationToRef(space, mesh, result);
  78970. return result;
  78971. };
  78972. /**
  78973. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78974. * @param space The space that the rotation should be in
  78975. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78976. * @param result The vector3 that the rotation should be copied to
  78977. */
  78978. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78980. if (mesh === void 0) { mesh = null; }
  78981. var quat = Bone._tmpQuat;
  78982. this.getRotationQuaternionToRef(space, mesh, quat);
  78983. quat.toEulerAnglesToRef(result);
  78984. };
  78985. /**
  78986. * Get the quaternion rotation of the bone in either local or world space
  78987. * @param space The space that the rotation should be in
  78988. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78989. * @returns The quaternion rotation
  78990. */
  78991. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78993. if (mesh === void 0) { mesh = null; }
  78994. var result = BABYLON.Quaternion.Identity();
  78995. this.getRotationQuaternionToRef(space, mesh, result);
  78996. return result;
  78997. };
  78998. /**
  78999. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79000. * @param space The space that the rotation should be in
  79001. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79002. * @param result The quaternion that the rotation should be copied to
  79003. */
  79004. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79006. if (mesh === void 0) { mesh = null; }
  79007. if (space == BABYLON.Space.LOCAL) {
  79008. this._decompose();
  79009. result.copyFrom(this._localRotation);
  79010. }
  79011. else {
  79012. var mat = Bone._tmpMats[0];
  79013. var amat = this.getAbsoluteTransform();
  79014. if (mesh) {
  79015. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79016. }
  79017. else {
  79018. mat.copyFrom(amat);
  79019. }
  79020. mat.m[0] *= this._scalingDeterminant;
  79021. mat.m[1] *= this._scalingDeterminant;
  79022. mat.m[2] *= this._scalingDeterminant;
  79023. mat.decompose(undefined, result, undefined);
  79024. }
  79025. };
  79026. /**
  79027. * Get the rotation matrix of the bone in local or world space
  79028. * @param space The space that the rotation should be in
  79029. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79030. * @returns The rotation matrix
  79031. */
  79032. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79034. var result = BABYLON.Matrix.Identity();
  79035. this.getRotationMatrixToRef(space, mesh, result);
  79036. return result;
  79037. };
  79038. /**
  79039. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79040. * @param space The space that the rotation should be in
  79041. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79042. * @param result The quaternion that the rotation should be copied to
  79043. */
  79044. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79045. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79046. if (space == BABYLON.Space.LOCAL) {
  79047. this.getLocalMatrix().getRotationMatrixToRef(result);
  79048. }
  79049. else {
  79050. var mat = Bone._tmpMats[0];
  79051. var amat = this.getAbsoluteTransform();
  79052. if (mesh) {
  79053. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79054. }
  79055. else {
  79056. mat.copyFrom(amat);
  79057. }
  79058. mat.m[0] *= this._scalingDeterminant;
  79059. mat.m[1] *= this._scalingDeterminant;
  79060. mat.m[2] *= this._scalingDeterminant;
  79061. mat.getRotationMatrixToRef(result);
  79062. }
  79063. };
  79064. /**
  79065. * Get the world position of a point that is in the local space of the bone
  79066. * @param position The local position
  79067. * @param mesh The mesh that this bone is attached to
  79068. * @returns The world position
  79069. */
  79070. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79071. if (mesh === void 0) { mesh = null; }
  79072. var result = BABYLON.Vector3.Zero();
  79073. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79074. return result;
  79075. };
  79076. /**
  79077. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79078. * @param position The local position
  79079. * @param mesh The mesh that this bone is attached to
  79080. * @param result The vector3 that the world position should be copied to
  79081. */
  79082. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79083. if (mesh === void 0) { mesh = null; }
  79084. var wm = null;
  79085. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79086. if (mesh) {
  79087. wm = mesh.getWorldMatrix();
  79088. }
  79089. this._skeleton.computeAbsoluteTransforms();
  79090. var tmat = Bone._tmpMats[0];
  79091. if (mesh && wm) {
  79092. tmat.copyFrom(this.getAbsoluteTransform());
  79093. tmat.multiplyToRef(wm, tmat);
  79094. }
  79095. else {
  79096. tmat = this.getAbsoluteTransform();
  79097. }
  79098. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79099. };
  79100. /**
  79101. * Get the local position of a point that is in world space
  79102. * @param position The world position
  79103. * @param mesh The mesh that this bone is attached to
  79104. * @returns The local position
  79105. */
  79106. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79107. if (mesh === void 0) { mesh = null; }
  79108. var result = BABYLON.Vector3.Zero();
  79109. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79110. return result;
  79111. };
  79112. /**
  79113. * Get the local position of a point that is in world space and copy it to the result param
  79114. * @param position The world position
  79115. * @param mesh The mesh that this bone is attached to
  79116. * @param result The vector3 that the local position should be copied to
  79117. */
  79118. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79119. if (mesh === void 0) { mesh = null; }
  79120. var wm = null;
  79121. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79122. if (mesh) {
  79123. wm = mesh.getWorldMatrix();
  79124. }
  79125. this._skeleton.computeAbsoluteTransforms();
  79126. var tmat = Bone._tmpMats[0];
  79127. tmat.copyFrom(this.getAbsoluteTransform());
  79128. if (mesh && wm) {
  79129. tmat.multiplyToRef(wm, tmat);
  79130. }
  79131. tmat.invert();
  79132. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79133. };
  79134. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79135. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79136. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79137. return Bone;
  79138. }(BABYLON.Node));
  79139. BABYLON.Bone = Bone;
  79140. })(BABYLON || (BABYLON = {}));
  79141. //# sourceMappingURL=babylon.bone.js.map
  79142. var BABYLON;
  79143. (function (BABYLON) {
  79144. /**
  79145. * Class used to apply inverse kinematics to bones
  79146. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79147. */
  79148. var BoneIKController = /** @class */ (function () {
  79149. /**
  79150. * Creates a new BoneIKController
  79151. * @param mesh defines the mesh to control
  79152. * @param bone defines the bone to control
  79153. * @param options defines options to set up the controller
  79154. */
  79155. function BoneIKController(mesh, bone, options) {
  79156. /**
  79157. * Gets or sets the target position
  79158. */
  79159. this.targetPosition = BABYLON.Vector3.Zero();
  79160. /**
  79161. * Gets or sets the pole target position
  79162. */
  79163. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79164. /**
  79165. * Gets or sets the pole target local offset
  79166. */
  79167. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79168. /**
  79169. * Gets or sets the pole angle
  79170. */
  79171. this.poleAngle = 0;
  79172. /**
  79173. * 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)
  79174. */
  79175. this.slerpAmount = 1;
  79176. this._bone1Quat = BABYLON.Quaternion.Identity();
  79177. this._bone1Mat = BABYLON.Matrix.Identity();
  79178. this._bone2Ang = Math.PI;
  79179. this._maxAngle = Math.PI;
  79180. this._rightHandedSystem = false;
  79181. this._bendAxis = BABYLON.Vector3.Right();
  79182. this._slerping = false;
  79183. this._adjustRoll = 0;
  79184. this._bone2 = bone;
  79185. this._bone1 = bone.getParent();
  79186. if (!this._bone1) {
  79187. return;
  79188. }
  79189. this.mesh = mesh;
  79190. var bonePos = bone.getPosition();
  79191. if (bone.getAbsoluteTransform().determinant() > 0) {
  79192. this._rightHandedSystem = true;
  79193. this._bendAxis.x = 0;
  79194. this._bendAxis.y = 0;
  79195. this._bendAxis.z = -1;
  79196. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79197. this._adjustRoll = Math.PI * .5;
  79198. this._bendAxis.z = 1;
  79199. }
  79200. }
  79201. if (this._bone1.length) {
  79202. var boneScale1 = this._bone1.getScale();
  79203. var boneScale2 = this._bone2.getScale();
  79204. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79205. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79206. }
  79207. else if (this._bone1.children[0]) {
  79208. mesh.computeWorldMatrix(true);
  79209. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79210. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79211. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79212. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79213. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79214. }
  79215. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79216. this.maxAngle = Math.PI;
  79217. if (options) {
  79218. if (options.targetMesh) {
  79219. this.targetMesh = options.targetMesh;
  79220. this.targetMesh.computeWorldMatrix(true);
  79221. }
  79222. if (options.poleTargetMesh) {
  79223. this.poleTargetMesh = options.poleTargetMesh;
  79224. this.poleTargetMesh.computeWorldMatrix(true);
  79225. }
  79226. else if (options.poleTargetBone) {
  79227. this.poleTargetBone = options.poleTargetBone;
  79228. }
  79229. else if (this._bone1.getParent()) {
  79230. this.poleTargetBone = this._bone1.getParent();
  79231. }
  79232. if (options.poleTargetLocalOffset) {
  79233. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79234. }
  79235. if (options.poleAngle) {
  79236. this.poleAngle = options.poleAngle;
  79237. }
  79238. if (options.bendAxis) {
  79239. this._bendAxis.copyFrom(options.bendAxis);
  79240. }
  79241. if (options.maxAngle) {
  79242. this.maxAngle = options.maxAngle;
  79243. }
  79244. if (options.slerpAmount) {
  79245. this.slerpAmount = options.slerpAmount;
  79246. }
  79247. }
  79248. }
  79249. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79250. /**
  79251. * Gets or sets maximum allowed angle
  79252. */
  79253. get: function () {
  79254. return this._maxAngle;
  79255. },
  79256. set: function (value) {
  79257. this._setMaxAngle(value);
  79258. },
  79259. enumerable: true,
  79260. configurable: true
  79261. });
  79262. BoneIKController.prototype._setMaxAngle = function (ang) {
  79263. if (ang < 0) {
  79264. ang = 0;
  79265. }
  79266. if (ang > Math.PI || ang == undefined) {
  79267. ang = Math.PI;
  79268. }
  79269. this._maxAngle = ang;
  79270. var a = this._bone1Length;
  79271. var b = this._bone2Length;
  79272. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79273. };
  79274. /**
  79275. * Force the controller to update the bones
  79276. */
  79277. BoneIKController.prototype.update = function () {
  79278. var bone1 = this._bone1;
  79279. if (!bone1) {
  79280. return;
  79281. }
  79282. var target = this.targetPosition;
  79283. var poleTarget = this.poleTargetPosition;
  79284. var mat1 = BoneIKController._tmpMats[0];
  79285. var mat2 = BoneIKController._tmpMats[1];
  79286. if (this.targetMesh) {
  79287. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79288. }
  79289. if (this.poleTargetBone) {
  79290. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79291. }
  79292. else if (this.poleTargetMesh) {
  79293. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79294. }
  79295. var bonePos = BoneIKController._tmpVecs[0];
  79296. var zaxis = BoneIKController._tmpVecs[1];
  79297. var xaxis = BoneIKController._tmpVecs[2];
  79298. var yaxis = BoneIKController._tmpVecs[3];
  79299. var upAxis = BoneIKController._tmpVecs[4];
  79300. var _tmpQuat = BoneIKController._tmpQuat;
  79301. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79302. poleTarget.subtractToRef(bonePos, upAxis);
  79303. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79304. upAxis.y = 1;
  79305. }
  79306. else {
  79307. upAxis.normalize();
  79308. }
  79309. target.subtractToRef(bonePos, yaxis);
  79310. yaxis.normalize();
  79311. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79312. zaxis.normalize();
  79313. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79314. xaxis.normalize();
  79315. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79316. var a = this._bone1Length;
  79317. var b = this._bone2Length;
  79318. var c = BABYLON.Vector3.Distance(bonePos, target);
  79319. if (this._maxReach > 0) {
  79320. c = Math.min(this._maxReach, c);
  79321. }
  79322. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79323. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79324. if (acosa > 1) {
  79325. acosa = 1;
  79326. }
  79327. if (acosb > 1) {
  79328. acosb = 1;
  79329. }
  79330. if (acosa < -1) {
  79331. acosa = -1;
  79332. }
  79333. if (acosb < -1) {
  79334. acosb = -1;
  79335. }
  79336. var angA = Math.acos(acosa);
  79337. var angB = Math.acos(acosb);
  79338. var angC = -angA - angB;
  79339. if (this._rightHandedSystem) {
  79340. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79341. mat2.multiplyToRef(mat1, mat1);
  79342. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79343. mat2.multiplyToRef(mat1, mat1);
  79344. }
  79345. else {
  79346. var _tmpVec = BoneIKController._tmpVecs[5];
  79347. _tmpVec.copyFrom(this._bendAxis);
  79348. _tmpVec.x *= -1;
  79349. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79350. mat2.multiplyToRef(mat1, mat1);
  79351. }
  79352. if (this.poleAngle) {
  79353. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79354. mat1.multiplyToRef(mat2, mat1);
  79355. }
  79356. if (this._bone1) {
  79357. if (this.slerpAmount < 1) {
  79358. if (!this._slerping) {
  79359. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79360. }
  79361. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79362. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79363. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79364. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79365. this._slerping = true;
  79366. }
  79367. else {
  79368. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79369. this._bone1Mat.copyFrom(mat1);
  79370. this._slerping = false;
  79371. }
  79372. }
  79373. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79374. this._bone2Ang = angC;
  79375. };
  79376. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79377. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79378. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79379. return BoneIKController;
  79380. }());
  79381. BABYLON.BoneIKController = BoneIKController;
  79382. })(BABYLON || (BABYLON = {}));
  79383. //# sourceMappingURL=babylon.boneIKController.js.map
  79384. var BABYLON;
  79385. (function (BABYLON) {
  79386. /**
  79387. * Class used to make a bone look toward a point in space
  79388. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79389. */
  79390. var BoneLookController = /** @class */ (function () {
  79391. /**
  79392. * Create a BoneLookController
  79393. * @param mesh the mesh that the bone belongs to
  79394. * @param bone the bone that will be looking to the target
  79395. * @param target the target Vector3 to look at
  79396. * @param settings optional settings:
  79397. * * maxYaw: the maximum angle the bone will yaw to
  79398. * * minYaw: the minimum angle the bone will yaw to
  79399. * * maxPitch: the maximum angle the bone will pitch to
  79400. * * minPitch: the minimum angle the bone will yaw to
  79401. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79402. * * upAxis: the up axis of the coordinate system
  79403. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79404. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79405. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79406. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79407. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79408. * * adjustRoll: used to make an adjustment to the roll of the bone
  79409. **/
  79410. function BoneLookController(mesh, bone, target, options) {
  79411. /**
  79412. * The up axis of the coordinate system that is used when the bone is rotated
  79413. */
  79414. this.upAxis = BABYLON.Vector3.Up();
  79415. /**
  79416. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79417. */
  79418. this.upAxisSpace = BABYLON.Space.LOCAL;
  79419. /**
  79420. * Used to make an adjustment to the yaw of the bone
  79421. */
  79422. this.adjustYaw = 0;
  79423. /**
  79424. * Used to make an adjustment to the pitch of the bone
  79425. */
  79426. this.adjustPitch = 0;
  79427. /**
  79428. * Used to make an adjustment to the roll of the bone
  79429. */
  79430. this.adjustRoll = 0;
  79431. /**
  79432. * 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)
  79433. */
  79434. this.slerpAmount = 1;
  79435. this._boneQuat = BABYLON.Quaternion.Identity();
  79436. this._slerping = false;
  79437. this._firstFrameSkipped = false;
  79438. this._fowardAxis = BABYLON.Vector3.Forward();
  79439. this.mesh = mesh;
  79440. this.bone = bone;
  79441. this.target = target;
  79442. if (options) {
  79443. if (options.adjustYaw) {
  79444. this.adjustYaw = options.adjustYaw;
  79445. }
  79446. if (options.adjustPitch) {
  79447. this.adjustPitch = options.adjustPitch;
  79448. }
  79449. if (options.adjustRoll) {
  79450. this.adjustRoll = options.adjustRoll;
  79451. }
  79452. if (options.maxYaw != null) {
  79453. this.maxYaw = options.maxYaw;
  79454. }
  79455. else {
  79456. this.maxYaw = Math.PI;
  79457. }
  79458. if (options.minYaw != null) {
  79459. this.minYaw = options.minYaw;
  79460. }
  79461. else {
  79462. this.minYaw = -Math.PI;
  79463. }
  79464. if (options.maxPitch != null) {
  79465. this.maxPitch = options.maxPitch;
  79466. }
  79467. else {
  79468. this.maxPitch = Math.PI;
  79469. }
  79470. if (options.minPitch != null) {
  79471. this.minPitch = options.minPitch;
  79472. }
  79473. else {
  79474. this.minPitch = -Math.PI;
  79475. }
  79476. if (options.slerpAmount != null) {
  79477. this.slerpAmount = options.slerpAmount;
  79478. }
  79479. if (options.upAxis != null) {
  79480. this.upAxis = options.upAxis;
  79481. }
  79482. if (options.upAxisSpace != null) {
  79483. this.upAxisSpace = options.upAxisSpace;
  79484. }
  79485. if (options.yawAxis != null || options.pitchAxis != null) {
  79486. var newYawAxis = BABYLON.Axis.Y;
  79487. var newPitchAxis = BABYLON.Axis.X;
  79488. if (options.yawAxis != null) {
  79489. newYawAxis = options.yawAxis.clone();
  79490. newYawAxis.normalize();
  79491. }
  79492. if (options.pitchAxis != null) {
  79493. newPitchAxis = options.pitchAxis.clone();
  79494. newPitchAxis.normalize();
  79495. }
  79496. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79497. this._transformYawPitch = BABYLON.Matrix.Identity();
  79498. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79499. this._transformYawPitchInv = this._transformYawPitch.clone();
  79500. this._transformYawPitch.invert();
  79501. }
  79502. }
  79503. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79504. this.upAxisSpace = BABYLON.Space.LOCAL;
  79505. }
  79506. }
  79507. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79508. /**
  79509. * Gets or sets the minimum yaw angle that the bone can look to
  79510. */
  79511. get: function () {
  79512. return this._minYaw;
  79513. },
  79514. set: function (value) {
  79515. this._minYaw = value;
  79516. this._minYawSin = Math.sin(value);
  79517. this._minYawCos = Math.cos(value);
  79518. if (this._maxYaw != null) {
  79519. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79520. this._yawRange = this._maxYaw - this._minYaw;
  79521. }
  79522. },
  79523. enumerable: true,
  79524. configurable: true
  79525. });
  79526. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79527. /**
  79528. * Gets or sets the maximum yaw angle that the bone can look to
  79529. */
  79530. get: function () {
  79531. return this._maxYaw;
  79532. },
  79533. set: function (value) {
  79534. this._maxYaw = value;
  79535. this._maxYawSin = Math.sin(value);
  79536. this._maxYawCos = Math.cos(value);
  79537. if (this._minYaw != null) {
  79538. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79539. this._yawRange = this._maxYaw - this._minYaw;
  79540. }
  79541. },
  79542. enumerable: true,
  79543. configurable: true
  79544. });
  79545. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79546. /**
  79547. * Gets or sets the minimum pitch angle that the bone can look to
  79548. */
  79549. get: function () {
  79550. return this._minPitch;
  79551. },
  79552. set: function (value) {
  79553. this._minPitch = value;
  79554. this._minPitchTan = Math.tan(value);
  79555. },
  79556. enumerable: true,
  79557. configurable: true
  79558. });
  79559. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79560. /**
  79561. * Gets or sets the maximum pitch angle that the bone can look to
  79562. */
  79563. get: function () {
  79564. return this._maxPitch;
  79565. },
  79566. set: function (value) {
  79567. this._maxPitch = value;
  79568. this._maxPitchTan = Math.tan(value);
  79569. },
  79570. enumerable: true,
  79571. configurable: true
  79572. });
  79573. /**
  79574. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79575. */
  79576. BoneLookController.prototype.update = function () {
  79577. //skip the first frame when slerping so that the mesh rotation is correct
  79578. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79579. this._firstFrameSkipped = true;
  79580. return;
  79581. }
  79582. var bone = this.bone;
  79583. var bonePos = BoneLookController._tmpVecs[0];
  79584. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79585. var target = this.target;
  79586. var _tmpMat1 = BoneLookController._tmpMats[0];
  79587. var _tmpMat2 = BoneLookController._tmpMats[1];
  79588. var mesh = this.mesh;
  79589. var parentBone = bone.getParent();
  79590. var upAxis = BoneLookController._tmpVecs[1];
  79591. upAxis.copyFrom(this.upAxis);
  79592. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79593. if (this._transformYawPitch) {
  79594. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79595. }
  79596. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79597. }
  79598. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79599. mesh.getDirectionToRef(upAxis, upAxis);
  79600. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79601. upAxis.normalize();
  79602. }
  79603. }
  79604. var checkYaw = false;
  79605. var checkPitch = false;
  79606. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79607. checkYaw = true;
  79608. }
  79609. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79610. checkPitch = true;
  79611. }
  79612. if (checkYaw || checkPitch) {
  79613. var spaceMat = BoneLookController._tmpMats[2];
  79614. var spaceMatInv = BoneLookController._tmpMats[3];
  79615. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79616. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79617. }
  79618. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79619. spaceMat.copyFrom(mesh.getWorldMatrix());
  79620. }
  79621. else {
  79622. var forwardAxis = BoneLookController._tmpVecs[2];
  79623. forwardAxis.copyFrom(this._fowardAxis);
  79624. if (this._transformYawPitch) {
  79625. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79626. }
  79627. if (parentBone) {
  79628. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79629. }
  79630. else {
  79631. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79632. }
  79633. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79634. rightAxis.normalize();
  79635. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79636. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79637. }
  79638. spaceMat.invertToRef(spaceMatInv);
  79639. var xzlen = null;
  79640. if (checkPitch) {
  79641. var localTarget = BoneLookController._tmpVecs[3];
  79642. target.subtractToRef(bonePos, localTarget);
  79643. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79644. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79645. var pitch = Math.atan2(localTarget.y, xzlen);
  79646. var newPitch = pitch;
  79647. if (pitch > this._maxPitch) {
  79648. localTarget.y = this._maxPitchTan * xzlen;
  79649. newPitch = this._maxPitch;
  79650. }
  79651. else if (pitch < this._minPitch) {
  79652. localTarget.y = this._minPitchTan * xzlen;
  79653. newPitch = this._minPitch;
  79654. }
  79655. if (pitch != newPitch) {
  79656. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79657. localTarget.addInPlace(bonePos);
  79658. target = localTarget;
  79659. }
  79660. }
  79661. if (checkYaw) {
  79662. var localTarget = BoneLookController._tmpVecs[4];
  79663. target.subtractToRef(bonePos, localTarget);
  79664. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79665. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79666. var newYaw = yaw;
  79667. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79668. if (xzlen == null) {
  79669. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79670. }
  79671. if (this._yawRange > Math.PI) {
  79672. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79673. localTarget.z = this._maxYawCos * xzlen;
  79674. localTarget.x = this._maxYawSin * xzlen;
  79675. newYaw = this._maxYaw;
  79676. }
  79677. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79678. localTarget.z = this._minYawCos * xzlen;
  79679. localTarget.x = this._minYawSin * xzlen;
  79680. newYaw = this._minYaw;
  79681. }
  79682. }
  79683. else {
  79684. if (yaw > this._maxYaw) {
  79685. localTarget.z = this._maxYawCos * xzlen;
  79686. localTarget.x = this._maxYawSin * xzlen;
  79687. newYaw = this._maxYaw;
  79688. }
  79689. else if (yaw < this._minYaw) {
  79690. localTarget.z = this._minYawCos * xzlen;
  79691. localTarget.x = this._minYawSin * xzlen;
  79692. newYaw = this._minYaw;
  79693. }
  79694. }
  79695. }
  79696. if (this._slerping && this._yawRange > Math.PI) {
  79697. //are we going to be crossing into the min/max region?
  79698. var boneFwd = BoneLookController._tmpVecs[8];
  79699. boneFwd.copyFrom(BABYLON.Axis.Z);
  79700. if (this._transformYawPitch) {
  79701. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79702. }
  79703. var boneRotMat = BoneLookController._tmpMats[4];
  79704. this._boneQuat.toRotationMatrix(boneRotMat);
  79705. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79706. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79707. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79708. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79709. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79710. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79711. if (angBtwTar > angBtwMidYaw) {
  79712. if (xzlen == null) {
  79713. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79714. }
  79715. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79716. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79717. if (angBtwMin < angBtwMax) {
  79718. newYaw = boneYaw + Math.PI * .75;
  79719. localTarget.z = Math.cos(newYaw) * xzlen;
  79720. localTarget.x = Math.sin(newYaw) * xzlen;
  79721. }
  79722. else {
  79723. newYaw = boneYaw - Math.PI * .75;
  79724. localTarget.z = Math.cos(newYaw) * xzlen;
  79725. localTarget.x = Math.sin(newYaw) * xzlen;
  79726. }
  79727. }
  79728. }
  79729. if (yaw != newYaw) {
  79730. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79731. localTarget.addInPlace(bonePos);
  79732. target = localTarget;
  79733. }
  79734. }
  79735. }
  79736. var zaxis = BoneLookController._tmpVecs[5];
  79737. var xaxis = BoneLookController._tmpVecs[6];
  79738. var yaxis = BoneLookController._tmpVecs[7];
  79739. var _tmpQuat = BoneLookController._tmpQuat;
  79740. target.subtractToRef(bonePos, zaxis);
  79741. zaxis.normalize();
  79742. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79743. xaxis.normalize();
  79744. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79745. yaxis.normalize();
  79746. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79747. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79748. return;
  79749. }
  79750. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79751. return;
  79752. }
  79753. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79754. return;
  79755. }
  79756. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79757. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79758. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79759. }
  79760. if (this.slerpAmount < 1) {
  79761. if (!this._slerping) {
  79762. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79763. }
  79764. if (this._transformYawPitch) {
  79765. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79766. }
  79767. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79768. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79769. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79770. this._slerping = true;
  79771. }
  79772. else {
  79773. if (this._transformYawPitch) {
  79774. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79775. }
  79776. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79777. this._slerping = false;
  79778. }
  79779. };
  79780. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79781. var angDiff = ang2 - ang1;
  79782. angDiff %= Math.PI * 2;
  79783. if (angDiff > Math.PI) {
  79784. angDiff -= Math.PI * 2;
  79785. }
  79786. else if (angDiff < -Math.PI) {
  79787. angDiff += Math.PI * 2;
  79788. }
  79789. return angDiff;
  79790. };
  79791. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79792. ang1 %= (2 * Math.PI);
  79793. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79794. ang2 %= (2 * Math.PI);
  79795. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79796. var ab = 0;
  79797. if (ang1 < ang2) {
  79798. ab = ang2 - ang1;
  79799. }
  79800. else {
  79801. ab = ang1 - ang2;
  79802. }
  79803. if (ab > Math.PI) {
  79804. ab = Math.PI * 2 - ab;
  79805. }
  79806. return ab;
  79807. };
  79808. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79809. ang %= (2 * Math.PI);
  79810. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79811. ang1 %= (2 * Math.PI);
  79812. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79813. ang2 %= (2 * Math.PI);
  79814. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79815. if (ang1 < ang2) {
  79816. if (ang > ang1 && ang < ang2) {
  79817. return true;
  79818. }
  79819. }
  79820. else {
  79821. if (ang > ang2 && ang < ang1) {
  79822. return true;
  79823. }
  79824. }
  79825. return false;
  79826. };
  79827. 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()];
  79828. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79829. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79830. return BoneLookController;
  79831. }());
  79832. BABYLON.BoneLookController = BoneLookController;
  79833. })(BABYLON || (BABYLON = {}));
  79834. //# sourceMappingURL=babylon.boneLookController.js.map
  79835. var BABYLON;
  79836. (function (BABYLON) {
  79837. /**
  79838. * Class used to handle skinning animations
  79839. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79840. */
  79841. var Skeleton = /** @class */ (function () {
  79842. /**
  79843. * Creates a new skeleton
  79844. * @param name defines the skeleton name
  79845. * @param id defines the skeleton Id
  79846. * @param scene defines the hosting scene
  79847. */
  79848. function Skeleton(
  79849. /** defines the skeleton name */
  79850. name,
  79851. /** defines the skeleton Id */
  79852. id, scene) {
  79853. this.name = name;
  79854. this.id = id;
  79855. /**
  79856. * Gets the list of child bones
  79857. */
  79858. this.bones = new Array();
  79859. /**
  79860. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79861. */
  79862. this.needInitialSkinMatrix = false;
  79863. this._isDirty = true;
  79864. this._meshesWithPoseMatrix = new Array();
  79865. this._identity = BABYLON.Matrix.Identity();
  79866. this._ranges = {};
  79867. this._lastAbsoluteTransformsUpdateId = -1;
  79868. /**
  79869. * Specifies if the skeleton should be serialized
  79870. */
  79871. this.doNotSerialize = false;
  79872. this._animationPropertiesOverride = null;
  79873. // Events
  79874. /**
  79875. * An observable triggered before computing the skeleton's matrices
  79876. */
  79877. this.onBeforeComputeObservable = new BABYLON.Observable();
  79878. this.bones = [];
  79879. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79880. scene.skeletons.push(this);
  79881. //make sure it will recalculate the matrix next time prepare is called.
  79882. this._isDirty = true;
  79883. }
  79884. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79885. /**
  79886. * Gets or sets the animation properties override
  79887. */
  79888. get: function () {
  79889. if (!this._animationPropertiesOverride) {
  79890. return this._scene.animationPropertiesOverride;
  79891. }
  79892. return this._animationPropertiesOverride;
  79893. },
  79894. set: function (value) {
  79895. this._animationPropertiesOverride = value;
  79896. },
  79897. enumerable: true,
  79898. configurable: true
  79899. });
  79900. // Members
  79901. /**
  79902. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79903. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79904. * @returns a Float32Array containing matrices data
  79905. */
  79906. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79907. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79908. return mesh._bonesTransformMatrices;
  79909. }
  79910. if (!this._transformMatrices) {
  79911. this.prepare();
  79912. }
  79913. return this._transformMatrices;
  79914. };
  79915. /**
  79916. * Gets the current hosting scene
  79917. * @returns a scene object
  79918. */
  79919. Skeleton.prototype.getScene = function () {
  79920. return this._scene;
  79921. };
  79922. // Methods
  79923. /**
  79924. * Gets a string representing the current skeleton data
  79925. * @param fullDetails defines a boolean indicating if we want a verbose version
  79926. * @returns a string representing the current skeleton data
  79927. */
  79928. Skeleton.prototype.toString = function (fullDetails) {
  79929. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79930. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79931. if (fullDetails) {
  79932. ret += ", Ranges: {";
  79933. var first = true;
  79934. for (var name_1 in this._ranges) {
  79935. if (first) {
  79936. ret += ", ";
  79937. first = false;
  79938. }
  79939. ret += name_1;
  79940. }
  79941. ret += "}";
  79942. }
  79943. return ret;
  79944. };
  79945. /**
  79946. * Get bone's index searching by name
  79947. * @param name defines bone's name to search for
  79948. * @return the indice of the bone. Returns -1 if not found
  79949. */
  79950. Skeleton.prototype.getBoneIndexByName = function (name) {
  79951. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79952. if (this.bones[boneIndex].name === name) {
  79953. return boneIndex;
  79954. }
  79955. }
  79956. return -1;
  79957. };
  79958. /**
  79959. * Creater a new animation range
  79960. * @param name defines the name of the range
  79961. * @param from defines the start key
  79962. * @param to defines the end key
  79963. */
  79964. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79965. // check name not already in use
  79966. if (!this._ranges[name]) {
  79967. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79968. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79969. if (this.bones[i].animations[0]) {
  79970. this.bones[i].animations[0].createRange(name, from, to);
  79971. }
  79972. }
  79973. }
  79974. };
  79975. /**
  79976. * Delete a specific animation range
  79977. * @param name defines the name of the range
  79978. * @param deleteFrames defines if frames must be removed as well
  79979. */
  79980. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79981. if (deleteFrames === void 0) { deleteFrames = true; }
  79982. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79983. if (this.bones[i].animations[0]) {
  79984. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79985. }
  79986. }
  79987. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79988. };
  79989. /**
  79990. * Gets a specific animation range
  79991. * @param name defines the name of the range to look for
  79992. * @returns the requested animation range or null if not found
  79993. */
  79994. Skeleton.prototype.getAnimationRange = function (name) {
  79995. return this._ranges[name];
  79996. };
  79997. /**
  79998. * Gets the list of all animation ranges defined on this skeleton
  79999. * @returns an array
  80000. */
  80001. Skeleton.prototype.getAnimationRanges = function () {
  80002. var animationRanges = [];
  80003. var name;
  80004. var i = 0;
  80005. for (name in this._ranges) {
  80006. animationRanges[i] = this._ranges[name];
  80007. i++;
  80008. }
  80009. return animationRanges;
  80010. };
  80011. /**
  80012. * Copy animation range from a source skeleton.
  80013. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80014. * @param source defines the source skeleton
  80015. * @param name defines the name of the range to copy
  80016. * @param rescaleAsRequired defines if rescaling must be applied if required
  80017. * @returns true if operation was successful
  80018. */
  80019. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80020. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80021. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80022. return false;
  80023. }
  80024. var ret = true;
  80025. var frameOffset = this._getHighestAnimationFrame() + 1;
  80026. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80027. var boneDict = {};
  80028. var sourceBones = source.bones;
  80029. var nBones;
  80030. var i;
  80031. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80032. boneDict[sourceBones[i].name] = sourceBones[i];
  80033. }
  80034. if (this.bones.length !== sourceBones.length) {
  80035. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80036. ret = false;
  80037. }
  80038. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80039. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80040. var boneName = this.bones[i].name;
  80041. var sourceBone = boneDict[boneName];
  80042. if (sourceBone) {
  80043. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80044. }
  80045. else {
  80046. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80047. ret = false;
  80048. }
  80049. }
  80050. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80051. var range = source.getAnimationRange(name);
  80052. if (range) {
  80053. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80054. }
  80055. return ret;
  80056. };
  80057. /**
  80058. * Forces the skeleton to go to rest pose
  80059. */
  80060. Skeleton.prototype.returnToRest = function () {
  80061. for (var index = 0; index < this.bones.length; index++) {
  80062. this.bones[index].returnToRest();
  80063. }
  80064. };
  80065. Skeleton.prototype._getHighestAnimationFrame = function () {
  80066. var ret = 0;
  80067. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80068. if (this.bones[i].animations[0]) {
  80069. var highest = this.bones[i].animations[0].getHighestFrame();
  80070. if (ret < highest) {
  80071. ret = highest;
  80072. }
  80073. }
  80074. }
  80075. return ret;
  80076. };
  80077. /**
  80078. * Begin a specific animation range
  80079. * @param name defines the name of the range to start
  80080. * @param loop defines if looping must be turned on (false by default)
  80081. * @param speedRatio defines the speed ratio to apply (1 by default)
  80082. * @param onAnimationEnd defines a callback which will be called when animation will end
  80083. * @returns a new animatable
  80084. */
  80085. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80086. var range = this.getAnimationRange(name);
  80087. if (!range) {
  80088. return null;
  80089. }
  80090. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80091. };
  80092. /** @hidden */
  80093. Skeleton.prototype._markAsDirty = function () {
  80094. this._isDirty = true;
  80095. };
  80096. /** @hidden */
  80097. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80098. this._meshesWithPoseMatrix.push(mesh);
  80099. };
  80100. /** @hidden */
  80101. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80102. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80103. if (index > -1) {
  80104. this._meshesWithPoseMatrix.splice(index, 1);
  80105. }
  80106. };
  80107. /** @hidden */
  80108. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80109. this.onBeforeComputeObservable.notifyObservers(this);
  80110. for (var index = 0; index < this.bones.length; index++) {
  80111. var bone = this.bones[index];
  80112. var parentBone = bone.getParent();
  80113. if (parentBone) {
  80114. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80115. }
  80116. else {
  80117. if (initialSkinMatrix) {
  80118. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80119. }
  80120. else {
  80121. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80122. }
  80123. }
  80124. if (bone._index !== -1) {
  80125. var mappedIndex = bone._index === null ? index : bone._index;
  80126. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80127. }
  80128. }
  80129. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80130. };
  80131. /**
  80132. * Build all resources required to render a skeleton
  80133. */
  80134. Skeleton.prototype.prepare = function () {
  80135. if (!this._isDirty) {
  80136. return;
  80137. }
  80138. if (this.needInitialSkinMatrix) {
  80139. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80140. var mesh = this._meshesWithPoseMatrix[index];
  80141. var poseMatrix = mesh.getPoseMatrix();
  80142. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80143. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80144. }
  80145. if (this._synchronizedWithMesh !== mesh) {
  80146. this._synchronizedWithMesh = mesh;
  80147. // Prepare bones
  80148. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80149. var bone = this.bones[boneIndex];
  80150. if (!bone.getParent()) {
  80151. var matrix = bone.getBaseMatrix();
  80152. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80153. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80154. }
  80155. }
  80156. }
  80157. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80158. }
  80159. }
  80160. else {
  80161. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80162. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80163. }
  80164. this._computeTransformMatrices(this._transformMatrices, null);
  80165. }
  80166. this._isDirty = false;
  80167. this._scene._activeBones.addCount(this.bones.length, false);
  80168. };
  80169. /**
  80170. * Gets the list of animatables currently running for this skeleton
  80171. * @returns an array of animatables
  80172. */
  80173. Skeleton.prototype.getAnimatables = function () {
  80174. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80175. this._animatables = [];
  80176. for (var index = 0; index < this.bones.length; index++) {
  80177. this._animatables.push(this.bones[index]);
  80178. }
  80179. }
  80180. return this._animatables;
  80181. };
  80182. /**
  80183. * Clone the current skeleton
  80184. * @param name defines the name of the new skeleton
  80185. * @param id defines the id of the enw skeleton
  80186. * @returns the new skeleton
  80187. */
  80188. Skeleton.prototype.clone = function (name, id) {
  80189. var result = new Skeleton(name, id || name, this._scene);
  80190. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80191. for (var index = 0; index < this.bones.length; index++) {
  80192. var source = this.bones[index];
  80193. var parentBone = null;
  80194. var parent_1 = source.getParent();
  80195. if (parent_1) {
  80196. var parentIndex = this.bones.indexOf(parent_1);
  80197. parentBone = result.bones[parentIndex];
  80198. }
  80199. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80200. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80201. }
  80202. if (this._ranges) {
  80203. result._ranges = {};
  80204. for (var rangeName in this._ranges) {
  80205. var range = this._ranges[rangeName];
  80206. if (range) {
  80207. result._ranges[rangeName] = range.clone();
  80208. }
  80209. }
  80210. }
  80211. this._isDirty = true;
  80212. return result;
  80213. };
  80214. /**
  80215. * Enable animation blending for this skeleton
  80216. * @param blendingSpeed defines the blending speed to apply
  80217. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80218. */
  80219. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80220. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80221. this.bones.forEach(function (bone) {
  80222. bone.animations.forEach(function (animation) {
  80223. animation.enableBlending = true;
  80224. animation.blendingSpeed = blendingSpeed;
  80225. });
  80226. });
  80227. };
  80228. /**
  80229. * Releases all resources associated with the current skeleton
  80230. */
  80231. Skeleton.prototype.dispose = function () {
  80232. this._meshesWithPoseMatrix = [];
  80233. // Animations
  80234. this.getScene().stopAnimation(this);
  80235. // Remove from scene
  80236. this.getScene().removeSkeleton(this);
  80237. };
  80238. /**
  80239. * Serialize the skeleton in a JSON object
  80240. * @returns a JSON object
  80241. */
  80242. Skeleton.prototype.serialize = function () {
  80243. var serializationObject = {};
  80244. serializationObject.name = this.name;
  80245. serializationObject.id = this.id;
  80246. if (this.dimensionsAtRest) {
  80247. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80248. }
  80249. serializationObject.bones = [];
  80250. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80251. for (var index = 0; index < this.bones.length; index++) {
  80252. var bone = this.bones[index];
  80253. var parent_2 = bone.getParent();
  80254. var serializedBone = {
  80255. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80256. name: bone.name,
  80257. matrix: bone.getBaseMatrix().toArray(),
  80258. rest: bone.getRestPose().toArray()
  80259. };
  80260. serializationObject.bones.push(serializedBone);
  80261. if (bone.length) {
  80262. serializedBone.length = bone.length;
  80263. }
  80264. if (bone.metadata) {
  80265. serializedBone.metadata = bone.metadata;
  80266. }
  80267. if (bone.animations && bone.animations.length > 0) {
  80268. serializedBone.animation = bone.animations[0].serialize();
  80269. }
  80270. serializationObject.ranges = [];
  80271. for (var name in this._ranges) {
  80272. var source = this._ranges[name];
  80273. if (!source) {
  80274. continue;
  80275. }
  80276. var range = {};
  80277. range.name = name;
  80278. range.from = source.from;
  80279. range.to = source.to;
  80280. serializationObject.ranges.push(range);
  80281. }
  80282. }
  80283. return serializationObject;
  80284. };
  80285. /**
  80286. * Creates a new skeleton from serialized data
  80287. * @param parsedSkeleton defines the serialized data
  80288. * @param scene defines the hosting scene
  80289. * @returns a new skeleton
  80290. */
  80291. Skeleton.Parse = function (parsedSkeleton, scene) {
  80292. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80293. if (parsedSkeleton.dimensionsAtRest) {
  80294. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80295. }
  80296. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80297. var index;
  80298. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80299. var parsedBone = parsedSkeleton.bones[index];
  80300. var parentBone = null;
  80301. if (parsedBone.parentBoneIndex > -1) {
  80302. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80303. }
  80304. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80305. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80306. if (parsedBone.length) {
  80307. bone.length = parsedBone.length;
  80308. }
  80309. if (parsedBone.metadata) {
  80310. bone.metadata = parsedBone.metadata;
  80311. }
  80312. if (parsedBone.animation) {
  80313. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80314. }
  80315. }
  80316. // placed after bones, so createAnimationRange can cascade down
  80317. if (parsedSkeleton.ranges) {
  80318. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80319. var data = parsedSkeleton.ranges[index];
  80320. skeleton.createAnimationRange(data.name, data.from, data.to);
  80321. }
  80322. }
  80323. return skeleton;
  80324. };
  80325. /**
  80326. * Compute all node absolute transforms
  80327. * @param forceUpdate defines if computation must be done even if cache is up to date
  80328. */
  80329. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80330. if (forceUpdate === void 0) { forceUpdate = false; }
  80331. var renderId = this._scene.getRenderId();
  80332. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80333. this.bones[0].computeAbsoluteTransforms();
  80334. this._lastAbsoluteTransformsUpdateId = renderId;
  80335. }
  80336. };
  80337. /**
  80338. * Gets the root pose matrix
  80339. * @returns a matrix
  80340. */
  80341. Skeleton.prototype.getPoseMatrix = function () {
  80342. var poseMatrix = null;
  80343. if (this._meshesWithPoseMatrix.length > 0) {
  80344. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80345. }
  80346. return poseMatrix;
  80347. };
  80348. /**
  80349. * Sorts bones per internal index
  80350. */
  80351. Skeleton.prototype.sortBones = function () {
  80352. var bones = new Array();
  80353. var visited = new Array(this.bones.length);
  80354. for (var index = 0; index < this.bones.length; index++) {
  80355. this._sortBones(index, bones, visited);
  80356. }
  80357. this.bones = bones;
  80358. };
  80359. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80360. if (visited[index]) {
  80361. return;
  80362. }
  80363. visited[index] = true;
  80364. var bone = this.bones[index];
  80365. if (bone._index === undefined) {
  80366. bone._index = index;
  80367. }
  80368. var parentBone = bone.getParent();
  80369. if (parentBone) {
  80370. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80371. }
  80372. bones.push(bone);
  80373. };
  80374. return Skeleton;
  80375. }());
  80376. BABYLON.Skeleton = Skeleton;
  80377. })(BABYLON || (BABYLON = {}));
  80378. //# sourceMappingURL=babylon.skeleton.js.map
  80379. var BABYLON;
  80380. (function (BABYLON) {
  80381. var SphericalPolynomial = /** @class */ (function () {
  80382. function SphericalPolynomial() {
  80383. this.x = BABYLON.Vector3.Zero();
  80384. this.y = BABYLON.Vector3.Zero();
  80385. this.z = BABYLON.Vector3.Zero();
  80386. this.xx = BABYLON.Vector3.Zero();
  80387. this.yy = BABYLON.Vector3.Zero();
  80388. this.zz = BABYLON.Vector3.Zero();
  80389. this.xy = BABYLON.Vector3.Zero();
  80390. this.yz = BABYLON.Vector3.Zero();
  80391. this.zx = BABYLON.Vector3.Zero();
  80392. }
  80393. SphericalPolynomial.prototype.addAmbient = function (color) {
  80394. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80395. this.xx = this.xx.add(colorVector);
  80396. this.yy = this.yy.add(colorVector);
  80397. this.zz = this.zz.add(colorVector);
  80398. };
  80399. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80400. var result = new SphericalPolynomial();
  80401. result.x = harmonics.L11.scale(1.02333);
  80402. result.y = harmonics.L1_1.scale(1.02333);
  80403. result.z = harmonics.L10.scale(1.02333);
  80404. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80405. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80406. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80407. result.yz = harmonics.L2_1.scale(0.858086);
  80408. result.zx = harmonics.L21.scale(0.858086);
  80409. result.xy = harmonics.L2_2.scale(0.858086);
  80410. result.scale(1.0 / Math.PI);
  80411. return result;
  80412. };
  80413. SphericalPolynomial.prototype.scale = function (scale) {
  80414. this.x = this.x.scale(scale);
  80415. this.y = this.y.scale(scale);
  80416. this.z = this.z.scale(scale);
  80417. this.xx = this.xx.scale(scale);
  80418. this.yy = this.yy.scale(scale);
  80419. this.zz = this.zz.scale(scale);
  80420. this.yz = this.yz.scale(scale);
  80421. this.zx = this.zx.scale(scale);
  80422. this.xy = this.xy.scale(scale);
  80423. };
  80424. return SphericalPolynomial;
  80425. }());
  80426. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80427. var SphericalHarmonics = /** @class */ (function () {
  80428. function SphericalHarmonics() {
  80429. this.L00 = BABYLON.Vector3.Zero();
  80430. this.L1_1 = BABYLON.Vector3.Zero();
  80431. this.L10 = BABYLON.Vector3.Zero();
  80432. this.L11 = BABYLON.Vector3.Zero();
  80433. this.L2_2 = BABYLON.Vector3.Zero();
  80434. this.L2_1 = BABYLON.Vector3.Zero();
  80435. this.L20 = BABYLON.Vector3.Zero();
  80436. this.L21 = BABYLON.Vector3.Zero();
  80437. this.L22 = BABYLON.Vector3.Zero();
  80438. }
  80439. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80440. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80441. var c = colorVector.scale(deltaSolidAngle);
  80442. this.L00 = this.L00.add(c.scale(0.282095));
  80443. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80444. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80445. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80446. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80447. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80448. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80449. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80450. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80451. };
  80452. SphericalHarmonics.prototype.scale = function (scale) {
  80453. this.L00 = this.L00.scale(scale);
  80454. this.L1_1 = this.L1_1.scale(scale);
  80455. this.L10 = this.L10.scale(scale);
  80456. this.L11 = this.L11.scale(scale);
  80457. this.L2_2 = this.L2_2.scale(scale);
  80458. this.L2_1 = this.L2_1.scale(scale);
  80459. this.L20 = this.L20.scale(scale);
  80460. this.L21 = this.L21.scale(scale);
  80461. this.L22 = this.L22.scale(scale);
  80462. };
  80463. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80464. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80465. //
  80466. // E_lm = A_l * L_lm
  80467. //
  80468. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80469. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80470. // the scaling factors are given in equation 9.
  80471. // Constant (Band 0)
  80472. this.L00 = this.L00.scale(3.141593);
  80473. // Linear (Band 1)
  80474. this.L1_1 = this.L1_1.scale(2.094395);
  80475. this.L10 = this.L10.scale(2.094395);
  80476. this.L11 = this.L11.scale(2.094395);
  80477. // Quadratic (Band 2)
  80478. this.L2_2 = this.L2_2.scale(0.785398);
  80479. this.L2_1 = this.L2_1.scale(0.785398);
  80480. this.L20 = this.L20.scale(0.785398);
  80481. this.L21 = this.L21.scale(0.785398);
  80482. this.L22 = this.L22.scale(0.785398);
  80483. };
  80484. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80485. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80486. // L = (1/pi) * E * rho
  80487. //
  80488. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80489. this.scale(1.0 / Math.PI);
  80490. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80491. // (The pixel shader must apply albedo after texture fetches, etc).
  80492. };
  80493. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80494. var result = new SphericalHarmonics();
  80495. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80496. result.L1_1 = polynomial.y.scale(0.977204);
  80497. result.L10 = polynomial.z.scale(0.977204);
  80498. result.L11 = polynomial.x.scale(0.977204);
  80499. result.L2_2 = polynomial.xy.scale(1.16538);
  80500. result.L2_1 = polynomial.yz.scale(1.16538);
  80501. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80502. result.L21 = polynomial.zx.scale(1.16538);
  80503. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80504. result.scale(Math.PI);
  80505. return result;
  80506. };
  80507. return SphericalHarmonics;
  80508. }());
  80509. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80510. })(BABYLON || (BABYLON = {}));
  80511. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80512. var BABYLON;
  80513. (function (BABYLON) {
  80514. var FileFaceOrientation = /** @class */ (function () {
  80515. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80516. this.name = name;
  80517. this.worldAxisForNormal = worldAxisForNormal;
  80518. this.worldAxisForFileX = worldAxisForFileX;
  80519. this.worldAxisForFileY = worldAxisForFileY;
  80520. }
  80521. return FileFaceOrientation;
  80522. }());
  80523. ;
  80524. /**
  80525. * Helper class dealing with the extraction of spherical polynomial dataArray
  80526. * from a cube map.
  80527. */
  80528. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80529. function CubeMapToSphericalPolynomialTools() {
  80530. }
  80531. /**
  80532. * Converts a texture to the according Spherical Polynomial data.
  80533. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80534. *
  80535. * @param texture The texture to extract the information from.
  80536. * @return The Spherical Polynomial data.
  80537. */
  80538. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80539. if (!texture.isCube) {
  80540. // Only supports cube Textures currently.
  80541. return null;
  80542. }
  80543. var size = texture.getSize().width;
  80544. var right = texture.readPixels(0);
  80545. var left = texture.readPixels(1);
  80546. var up;
  80547. var down;
  80548. if (texture.isRenderTarget) {
  80549. up = texture.readPixels(3);
  80550. down = texture.readPixels(2);
  80551. }
  80552. else {
  80553. up = texture.readPixels(2);
  80554. down = texture.readPixels(3);
  80555. }
  80556. var front = texture.readPixels(4);
  80557. var back = texture.readPixels(5);
  80558. var gammaSpace = texture.gammaSpace;
  80559. // Always read as RGBA.
  80560. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80561. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80562. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80563. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80564. }
  80565. var cubeInfo = {
  80566. size: size,
  80567. right: right,
  80568. left: left,
  80569. up: up,
  80570. down: down,
  80571. front: front,
  80572. back: back,
  80573. format: format,
  80574. type: type,
  80575. gammaSpace: gammaSpace,
  80576. };
  80577. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80578. };
  80579. /**
  80580. * Converts a cubemap to the according Spherical Polynomial data.
  80581. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80582. *
  80583. * @param cubeInfo The Cube map to extract the information from.
  80584. * @return The Spherical Polynomial data.
  80585. */
  80586. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80587. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80588. var totalSolidAngle = 0.0;
  80589. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80590. var du = 2.0 / cubeInfo.size;
  80591. var dv = du;
  80592. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80593. var minUV = du * 0.5 - 1.0;
  80594. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80595. var fileFace = this.FileFaces[faceIndex];
  80596. var dataArray = cubeInfo[fileFace.name];
  80597. var v = minUV;
  80598. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80599. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80600. // Because SP is still linear, so summation is fine in that basis.
  80601. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80602. for (var y = 0; y < cubeInfo.size; y++) {
  80603. var u = minUV;
  80604. for (var x = 0; x < cubeInfo.size; x++) {
  80605. // World direction (not normalised)
  80606. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80607. worldDirection.normalize();
  80608. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80609. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80610. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80611. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80612. // Handle Integer types.
  80613. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80614. r /= 255;
  80615. g /= 255;
  80616. b /= 255;
  80617. }
  80618. // Handle Gamma space textures.
  80619. if (cubeInfo.gammaSpace) {
  80620. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80621. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80622. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80623. }
  80624. var color = new BABYLON.Color3(r, g, b);
  80625. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80626. totalSolidAngle += deltaSolidAngle;
  80627. u += du;
  80628. }
  80629. v += dv;
  80630. }
  80631. }
  80632. // Solid angle for entire sphere is 4*pi
  80633. var sphereSolidAngle = 4.0 * Math.PI;
  80634. // Adjust the solid angle to allow for how many faces we processed.
  80635. var facesProcessed = 6.0;
  80636. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80637. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80638. // This is needed because the numerical integration over the cube uses a
  80639. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80640. // and also to compensate for accumulative error due to float precision in the summation.
  80641. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80642. sphericalHarmonics.scale(correctionFactor);
  80643. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80644. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80645. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80646. };
  80647. CubeMapToSphericalPolynomialTools.FileFaces = [
  80648. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80649. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80650. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80651. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80652. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80653. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80654. ];
  80655. return CubeMapToSphericalPolynomialTools;
  80656. }());
  80657. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80658. })(BABYLON || (BABYLON = {}));
  80659. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80660. var BABYLON;
  80661. (function (BABYLON) {
  80662. /**
  80663. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80664. */
  80665. var PanoramaToCubeMapTools = /** @class */ (function () {
  80666. function PanoramaToCubeMapTools() {
  80667. }
  80668. /**
  80669. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80670. *
  80671. * @param float32Array The source data.
  80672. * @param inputWidth The width of the input panorama.
  80673. * @param inputhHeight The height of the input panorama.
  80674. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80675. * @return The cubemap data
  80676. */
  80677. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80678. if (!float32Array) {
  80679. throw "ConvertPanoramaToCubemap: input cannot be null";
  80680. }
  80681. if (float32Array.length != inputWidth * inputHeight * 3) {
  80682. throw "ConvertPanoramaToCubemap: input size is wrong";
  80683. }
  80684. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80685. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80686. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80687. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80688. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80689. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80690. return {
  80691. front: textureFront,
  80692. back: textureBack,
  80693. left: textureLeft,
  80694. right: textureRight,
  80695. up: textureUp,
  80696. down: textureDown,
  80697. size: size,
  80698. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80699. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80700. gammaSpace: false,
  80701. };
  80702. };
  80703. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80704. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80705. var textureArray = new Float32Array(buffer);
  80706. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80707. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80708. var dy = 1 / texSize;
  80709. var fy = 0;
  80710. for (var y = 0; y < texSize; y++) {
  80711. var xv1 = faceData[0];
  80712. var xv2 = faceData[2];
  80713. for (var x = 0; x < texSize; x++) {
  80714. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80715. v.normalize();
  80716. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80717. // 3 channels per pixels
  80718. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80719. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80720. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80721. xv1 = xv1.add(rotDX1);
  80722. xv2 = xv2.add(rotDX2);
  80723. }
  80724. fy += dy;
  80725. }
  80726. return textureArray;
  80727. };
  80728. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80729. var theta = Math.atan2(vDir.z, vDir.x);
  80730. var phi = Math.acos(vDir.y);
  80731. while (theta < -Math.PI)
  80732. theta += 2 * Math.PI;
  80733. while (theta > Math.PI)
  80734. theta -= 2 * Math.PI;
  80735. var dx = theta / Math.PI;
  80736. var dy = phi / Math.PI;
  80737. // recenter.
  80738. dx = dx * 0.5 + 0.5;
  80739. var px = Math.round(dx * inputWidth);
  80740. if (px < 0)
  80741. px = 0;
  80742. else if (px >= inputWidth)
  80743. px = inputWidth - 1;
  80744. var py = Math.round(dy * inputHeight);
  80745. if (py < 0)
  80746. py = 0;
  80747. else if (py >= inputHeight)
  80748. py = inputHeight - 1;
  80749. var inputY = (inputHeight - py - 1);
  80750. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80751. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80752. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80753. return {
  80754. r: r,
  80755. g: g,
  80756. b: b
  80757. };
  80758. };
  80759. PanoramaToCubeMapTools.FACE_FRONT = [
  80760. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80761. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80762. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80763. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80764. ];
  80765. PanoramaToCubeMapTools.FACE_BACK = [
  80766. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80767. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80768. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80769. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80770. ];
  80771. PanoramaToCubeMapTools.FACE_RIGHT = [
  80772. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80773. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80774. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80775. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80776. ];
  80777. PanoramaToCubeMapTools.FACE_LEFT = [
  80778. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80779. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80780. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80781. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80782. ];
  80783. PanoramaToCubeMapTools.FACE_DOWN = [
  80784. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80785. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80786. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80787. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80788. ];
  80789. PanoramaToCubeMapTools.FACE_UP = [
  80790. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80791. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80792. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80793. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80794. ];
  80795. return PanoramaToCubeMapTools;
  80796. }());
  80797. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80798. })(BABYLON || (BABYLON = {}));
  80799. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80800. var BABYLON;
  80801. (function (BABYLON) {
  80802. ;
  80803. /**
  80804. * This groups tools to convert HDR texture to native colors array.
  80805. */
  80806. var HDRTools = /** @class */ (function () {
  80807. function HDRTools() {
  80808. }
  80809. HDRTools.Ldexp = function (mantissa, exponent) {
  80810. if (exponent > 1023) {
  80811. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80812. }
  80813. if (exponent < -1074) {
  80814. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80815. }
  80816. return mantissa * Math.pow(2, exponent);
  80817. };
  80818. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80819. if (exponent > 0) { /*nonzero pixel*/
  80820. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80821. float32array[index + 0] = red * exponent;
  80822. float32array[index + 1] = green * exponent;
  80823. float32array[index + 2] = blue * exponent;
  80824. }
  80825. else {
  80826. float32array[index + 0] = 0;
  80827. float32array[index + 1] = 0;
  80828. float32array[index + 2] = 0;
  80829. }
  80830. };
  80831. HDRTools.readStringLine = function (uint8array, startIndex) {
  80832. var line = "";
  80833. var character = "";
  80834. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80835. character = String.fromCharCode(uint8array[i]);
  80836. if (character == "\n") {
  80837. break;
  80838. }
  80839. line += character;
  80840. }
  80841. return line;
  80842. };
  80843. /**
  80844. * Reads header information from an RGBE texture stored in a native array.
  80845. * More information on this format are available here:
  80846. * https://en.wikipedia.org/wiki/RGBE_image_format
  80847. *
  80848. * @param uint8array The binary file stored in native array.
  80849. * @return The header information.
  80850. */
  80851. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80852. var height = 0;
  80853. var width = 0;
  80854. var line = this.readStringLine(uint8array, 0);
  80855. if (line[0] != '#' || line[1] != '?') {
  80856. throw "Bad HDR Format.";
  80857. }
  80858. var endOfHeader = false;
  80859. var findFormat = false;
  80860. var lineIndex = 0;
  80861. do {
  80862. lineIndex += (line.length + 1);
  80863. line = this.readStringLine(uint8array, lineIndex);
  80864. if (line == "FORMAT=32-bit_rle_rgbe") {
  80865. findFormat = true;
  80866. }
  80867. else if (line.length == 0) {
  80868. endOfHeader = true;
  80869. }
  80870. } while (!endOfHeader);
  80871. if (!findFormat) {
  80872. throw "HDR Bad header format, unsupported FORMAT";
  80873. }
  80874. lineIndex += (line.length + 1);
  80875. line = this.readStringLine(uint8array, lineIndex);
  80876. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80877. var match = sizeRegexp.exec(line);
  80878. // TODO. Support +Y and -X if needed.
  80879. if (!match || match.length < 3) {
  80880. throw "HDR Bad header format, no size";
  80881. }
  80882. width = parseInt(match[2]);
  80883. height = parseInt(match[1]);
  80884. if (width < 8 || width > 0x7fff) {
  80885. throw "HDR Bad header format, unsupported size";
  80886. }
  80887. lineIndex += (line.length + 1);
  80888. return {
  80889. height: height,
  80890. width: width,
  80891. dataPosition: lineIndex
  80892. };
  80893. };
  80894. /**
  80895. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80896. * This RGBE texture needs to store the information as a panorama.
  80897. *
  80898. * More information on this format are available here:
  80899. * https://en.wikipedia.org/wiki/RGBE_image_format
  80900. *
  80901. * @param buffer The binary file stored in an array buffer.
  80902. * @param size The expected size of the extracted cubemap.
  80903. * @return The Cube Map information.
  80904. */
  80905. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80906. var uint8array = new Uint8Array(buffer);
  80907. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80908. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80909. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80910. return cubeMapData;
  80911. };
  80912. /**
  80913. * Returns the pixels data extracted from an RGBE texture.
  80914. * This pixels will be stored left to right up to down in the R G B order in one array.
  80915. *
  80916. * More information on this format are available here:
  80917. * https://en.wikipedia.org/wiki/RGBE_image_format
  80918. *
  80919. * @param uint8array The binary file stored in an array buffer.
  80920. * @param hdrInfo The header information of the file.
  80921. * @return The pixels data in RGB right to left up to down order.
  80922. */
  80923. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80924. // Keep for multi format supports.
  80925. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80926. };
  80927. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80928. var num_scanlines = hdrInfo.height;
  80929. var scanline_width = hdrInfo.width;
  80930. var a, b, c, d, count;
  80931. var dataIndex = hdrInfo.dataPosition;
  80932. var index = 0, endIndex = 0, i = 0;
  80933. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80934. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80935. // 3 channels of 4 bytes per pixel in float.
  80936. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80937. var resultArray = new Float32Array(resultBuffer);
  80938. // read in each successive scanline
  80939. while (num_scanlines > 0) {
  80940. a = uint8array[dataIndex++];
  80941. b = uint8array[dataIndex++];
  80942. c = uint8array[dataIndex++];
  80943. d = uint8array[dataIndex++];
  80944. if (a != 2 || b != 2 || (c & 0x80)) {
  80945. // this file is not run length encoded
  80946. throw "HDR Bad header format, not RLE";
  80947. }
  80948. if (((c << 8) | d) != scanline_width) {
  80949. throw "HDR Bad header format, wrong scan line width";
  80950. }
  80951. index = 0;
  80952. // read each of the four channels for the scanline into the buffer
  80953. for (i = 0; i < 4; i++) {
  80954. endIndex = (i + 1) * scanline_width;
  80955. while (index < endIndex) {
  80956. a = uint8array[dataIndex++];
  80957. b = uint8array[dataIndex++];
  80958. if (a > 128) {
  80959. // a run of the same value
  80960. count = a - 128;
  80961. if ((count == 0) || (count > endIndex - index)) {
  80962. throw "HDR Bad Format, bad scanline data (run)";
  80963. }
  80964. while (count-- > 0) {
  80965. scanLineArray[index++] = b;
  80966. }
  80967. }
  80968. else {
  80969. // a non-run
  80970. count = a;
  80971. if ((count == 0) || (count > endIndex - index)) {
  80972. throw "HDR Bad Format, bad scanline data (non-run)";
  80973. }
  80974. scanLineArray[index++] = b;
  80975. if (--count > 0) {
  80976. for (var j = 0; j < count; j++) {
  80977. scanLineArray[index++] = uint8array[dataIndex++];
  80978. }
  80979. }
  80980. }
  80981. }
  80982. }
  80983. // now convert data from buffer into floats
  80984. for (i = 0; i < scanline_width; i++) {
  80985. a = scanLineArray[i];
  80986. b = scanLineArray[i + scanline_width];
  80987. c = scanLineArray[i + 2 * scanline_width];
  80988. d = scanLineArray[i + 3 * scanline_width];
  80989. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80990. }
  80991. num_scanlines--;
  80992. }
  80993. return resultArray;
  80994. };
  80995. return HDRTools;
  80996. }());
  80997. BABYLON.HDRTools = HDRTools;
  80998. })(BABYLON || (BABYLON = {}));
  80999. //# sourceMappingURL=babylon.hdr.js.map
  81000. var BABYLON;
  81001. (function (BABYLON) {
  81002. /**
  81003. * Sets of helpers addressing the serialization and deserialization of environment texture
  81004. * stored in a BabylonJS env file.
  81005. * Those files are usually stored as .env files.
  81006. */
  81007. var EnvironmentTextureTools = /** @class */ (function () {
  81008. function EnvironmentTextureTools() {
  81009. }
  81010. /**
  81011. * Gets the environment info from an env file.
  81012. * @param data The array buffer containing the .env bytes.
  81013. * @returns the environment file info (the json header) if successfully parsed.
  81014. */
  81015. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81016. var dataView = new DataView(data);
  81017. var pos = 0;
  81018. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81019. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81020. BABYLON.Tools.Error('Not a babylon environment map');
  81021. return null;
  81022. }
  81023. }
  81024. // Read json manifest - collect characters up to null terminator
  81025. var manifestString = '';
  81026. var charCode = 0x00;
  81027. while ((charCode = dataView.getUint8(pos++))) {
  81028. manifestString += String.fromCharCode(charCode);
  81029. }
  81030. var manifest = JSON.parse(manifestString);
  81031. if (manifest.specular) {
  81032. // Extend the header with the position of the payload.
  81033. manifest.specular.specularDataPosition = pos;
  81034. }
  81035. return manifest;
  81036. };
  81037. /**
  81038. * Creates an environment texture from a loaded cube texture.
  81039. * @param texture defines the cube texture to convert in env file
  81040. * @return a promise containing the environment data if succesfull.
  81041. */
  81042. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81043. var _this = this;
  81044. var internalTexture = texture.getInternalTexture();
  81045. if (!internalTexture) {
  81046. return Promise.reject("The cube texture is invalid.");
  81047. }
  81048. if (!texture._prefiltered) {
  81049. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81050. }
  81051. var engine = internalTexture.getEngine();
  81052. if (engine && engine.premultipliedAlpha) {
  81053. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81054. }
  81055. var canvas = engine.getRenderingCanvas();
  81056. if (!canvas) {
  81057. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81058. }
  81059. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81060. if (!engine.getCaps().textureFloatRender) {
  81061. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81062. if (!engine.getCaps().textureHalfFloatRender) {
  81063. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81064. }
  81065. }
  81066. var cubeWidth = internalTexture.width;
  81067. var hostingScene = new BABYLON.Scene(engine);
  81068. var specularTextures = {};
  81069. var promises = [];
  81070. // Read and collect all mipmaps data from the cube.
  81071. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81072. mipmapsCount = Math.round(mipmapsCount);
  81073. var _loop_1 = function (i) {
  81074. var faceWidth = Math.pow(2, mipmapsCount - i);
  81075. var _loop_2 = function (face) {
  81076. var data = texture.readPixels(face, i);
  81077. // Creates a temp texture with the face data.
  81078. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81079. // And rgbdEncode them.
  81080. var promise = new Promise(function (resolve, reject) {
  81081. 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);
  81082. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81083. rgbdPostProcess.onApply = function (effect) {
  81084. effect._bindTexture("textureSampler", tempTexture);
  81085. };
  81086. // As the process needs to happen on the main canvas, keep track of the current size
  81087. var currentW = engine.getRenderWidth();
  81088. var currentH = engine.getRenderHeight();
  81089. // Set the desired size for the texture
  81090. engine.setSize(faceWidth, faceWidth);
  81091. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81092. // Reading datas from WebGL
  81093. canvas.toBlob(function (blob) {
  81094. var fileReader = new FileReader();
  81095. fileReader.onload = function (event) {
  81096. var arrayBuffer = event.target.result;
  81097. specularTextures[i * 6 + face] = arrayBuffer;
  81098. resolve();
  81099. };
  81100. fileReader.readAsArrayBuffer(blob);
  81101. });
  81102. // Reapply the previous canvas size
  81103. engine.setSize(currentW, currentH);
  81104. });
  81105. });
  81106. promises.push(promise);
  81107. };
  81108. // All faces of the cube.
  81109. for (var face = 0; face < 6; face++) {
  81110. _loop_2(face);
  81111. }
  81112. };
  81113. for (var i = 0; i <= mipmapsCount; i++) {
  81114. _loop_1(i);
  81115. }
  81116. // Once all the textures haves been collected as RGBD stored in PNGs
  81117. return Promise.all(promises).then(function () {
  81118. // We can delete the hosting scene keeping track of all the creation objects
  81119. hostingScene.dispose();
  81120. // Creates the json header for the env texture
  81121. var info = {
  81122. version: 1,
  81123. width: cubeWidth,
  81124. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81125. specular: {
  81126. mipmaps: []
  81127. }
  81128. };
  81129. // Sets the specular image data information
  81130. var position = 0;
  81131. for (var i = 0; i <= mipmapsCount; i++) {
  81132. for (var face = 0; face < 6; face++) {
  81133. var byteLength = specularTextures[i * 6 + face].byteLength;
  81134. info.specular.mipmaps.push({
  81135. length: byteLength,
  81136. position: position
  81137. });
  81138. position += byteLength;
  81139. }
  81140. }
  81141. // Encode the JSON as an array buffer
  81142. var infoString = JSON.stringify(info);
  81143. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81144. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81145. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81146. infoView[i] = infoString.charCodeAt(i);
  81147. }
  81148. // Ends up with a null terminator for easier parsing
  81149. infoView[infoString.length] = 0x00;
  81150. // Computes the final required size and creates the storage
  81151. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81152. var finalBuffer = new ArrayBuffer(totalSize);
  81153. var finalBufferView = new Uint8Array(finalBuffer);
  81154. var dataView = new DataView(finalBuffer);
  81155. // Copy the magic bytes identifying the file in
  81156. var pos = 0;
  81157. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81158. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81159. }
  81160. // Add the json info
  81161. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81162. pos += infoBuffer.byteLength;
  81163. // Finally inserts the texture data
  81164. for (var i = 0; i <= mipmapsCount; i++) {
  81165. for (var face = 0; face < 6; face++) {
  81166. var dataBuffer = specularTextures[i * 6 + face];
  81167. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81168. pos += dataBuffer.byteLength;
  81169. }
  81170. }
  81171. // Voila
  81172. return finalBuffer;
  81173. });
  81174. };
  81175. /**
  81176. * Creates a JSON representation of the spherical data.
  81177. * @param texture defines the texture containing the polynomials
  81178. * @return the JSON representation of the spherical info
  81179. */
  81180. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81181. var polynmials = texture.sphericalPolynomial;
  81182. if (polynmials == null) {
  81183. return null;
  81184. }
  81185. return {
  81186. polynomials: true,
  81187. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81188. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81189. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81190. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81191. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81192. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81193. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81194. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81195. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81196. };
  81197. };
  81198. /**
  81199. * Uploads the texture info contained in the env file to te GPU.
  81200. * @param texture defines the internal texture to upload to
  81201. * @param arrayBuffer defines the buffer cotaining the data to load
  81202. * @param info defines the texture info retrieved through the GetEnvInfo method
  81203. * @returns a promise
  81204. */
  81205. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81206. if (info.version !== 1) {
  81207. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81208. }
  81209. var specularInfo = info.specular;
  81210. if (!specularInfo) {
  81211. // Nothing else parsed so far
  81212. return Promise.resolve();
  81213. }
  81214. // Double checks the enclosed info
  81215. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81216. mipmapsCount = Math.round(mipmapsCount) + 1;
  81217. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81218. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81219. }
  81220. // Gets everything ready.
  81221. var engine = texture.getEngine();
  81222. var expandTexture = false;
  81223. var generateNonLODTextures = false;
  81224. var rgbdPostProcess = null;
  81225. var cubeRtt = null;
  81226. var lodTextures = null;
  81227. var caps = engine.getCaps();
  81228. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81229. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81230. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81231. // Add extra process if texture lod is not supported
  81232. if (!caps.textureLOD) {
  81233. expandTexture = false;
  81234. generateNonLODTextures = true;
  81235. lodTextures = {};
  81236. }
  81237. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81238. else if (engine.webGLVersion < 2) {
  81239. expandTexture = false;
  81240. }
  81241. // If half float available we can uncompress the texture
  81242. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81243. expandTexture = true;
  81244. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81245. }
  81246. // If full float available we can uncompress the texture
  81247. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81248. expandTexture = true;
  81249. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81250. }
  81251. // Expand the texture if possible
  81252. if (expandTexture) {
  81253. // Simply run through the decode PP
  81254. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81255. texture._isRGBD = false;
  81256. texture.invertY = false;
  81257. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81258. generateDepthBuffer: false,
  81259. generateMipMaps: true,
  81260. generateStencilBuffer: false,
  81261. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81262. type: texture.type,
  81263. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81264. });
  81265. }
  81266. else {
  81267. texture._isRGBD = true;
  81268. texture.invertY = true;
  81269. // In case of missing support, applies the same patch than DDS files.
  81270. if (generateNonLODTextures) {
  81271. var mipSlices = 3;
  81272. var scale = texture._lodGenerationScale;
  81273. var offset = texture._lodGenerationOffset;
  81274. for (var i = 0; i < mipSlices; i++) {
  81275. //compute LOD from even spacing in smoothness (matching shader calculation)
  81276. var smoothness = i / (mipSlices - 1);
  81277. var roughness = 1 - smoothness;
  81278. var minLODIndex = offset; // roughness = 0
  81279. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81280. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81281. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81282. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81283. glTextureFromLod.isCube = true;
  81284. glTextureFromLod.invertY = true;
  81285. glTextureFromLod.generateMipMaps = false;
  81286. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81287. // Wrap in a base texture for easy binding.
  81288. var lodTexture = new BABYLON.BaseTexture(null);
  81289. lodTexture.isCube = true;
  81290. lodTexture._texture = glTextureFromLod;
  81291. lodTextures[mipmapIndex] = lodTexture;
  81292. switch (i) {
  81293. case 0:
  81294. texture._lodTextureLow = lodTexture;
  81295. break;
  81296. case 1:
  81297. texture._lodTextureMid = lodTexture;
  81298. break;
  81299. case 2:
  81300. texture._lodTextureHigh = lodTexture;
  81301. break;
  81302. }
  81303. }
  81304. }
  81305. }
  81306. var promises = [];
  81307. var _loop_3 = function (i) {
  81308. var _loop_4 = function (face) {
  81309. // Retrieves the face data
  81310. var imageData = specularInfo.mipmaps[i * 6 + face];
  81311. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81312. // Constructs an image element from bytes
  81313. var blob = new Blob([bytes], { type: 'image/png' });
  81314. var url = URL.createObjectURL(blob);
  81315. var image = new Image();
  81316. image.src = url;
  81317. // Enqueue promise to upload to the texture.
  81318. var promise = new Promise(function (resolve, reject) {
  81319. ;
  81320. image.onload = function () {
  81321. if (expandTexture) {
  81322. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81323. reject(message);
  81324. }, image);
  81325. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81326. // Uncompress the data to a RTT
  81327. rgbdPostProcess.onApply = function (effect) {
  81328. effect._bindTexture("textureSampler", tempTexture_1);
  81329. effect.setFloat2("scale", 1, 1);
  81330. };
  81331. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81332. // Cleanup
  81333. engine.restoreDefaultFramebuffer();
  81334. tempTexture_1.dispose();
  81335. window.URL.revokeObjectURL(url);
  81336. resolve();
  81337. });
  81338. }
  81339. else {
  81340. engine._uploadImageToTexture(texture, face, i, image);
  81341. // Upload the face to the none lod texture support
  81342. if (generateNonLODTextures) {
  81343. var lodTexture = lodTextures[i];
  81344. if (lodTexture) {
  81345. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81346. }
  81347. }
  81348. resolve();
  81349. }
  81350. };
  81351. image.onerror = function (error) {
  81352. reject(error);
  81353. };
  81354. });
  81355. promises.push(promise);
  81356. };
  81357. // All faces
  81358. for (var face = 0; face < 6; face++) {
  81359. _loop_4(face);
  81360. }
  81361. };
  81362. // All mipmaps
  81363. for (var i = 0; i < mipmapsCount; i++) {
  81364. _loop_3(i);
  81365. }
  81366. // Once all done, finishes the cleanup and return
  81367. return Promise.all(promises).then(function () {
  81368. // Relase temp RTT.
  81369. if (cubeRtt) {
  81370. engine._releaseFramebufferObjects(cubeRtt);
  81371. cubeRtt._swapAndDie(texture);
  81372. }
  81373. // Relase temp Post Process.
  81374. if (rgbdPostProcess) {
  81375. rgbdPostProcess.dispose();
  81376. }
  81377. // Flag internal texture as ready in case they are in use.
  81378. if (generateNonLODTextures) {
  81379. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81380. texture._lodTextureHigh._texture.isReady = true;
  81381. }
  81382. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81383. texture._lodTextureMid._texture.isReady = true;
  81384. }
  81385. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81386. texture._lodTextureLow._texture.isReady = true;
  81387. }
  81388. }
  81389. });
  81390. };
  81391. /**
  81392. * Uploads spherical polynomials information to the texture.
  81393. * @param texture defines the texture we are trying to upload the information to
  81394. * @param arrayBuffer defines the array buffer holding the data
  81395. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81396. */
  81397. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81398. if (info.version !== 1) {
  81399. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81400. }
  81401. var irradianceInfo = info.irradiance;
  81402. if (!irradianceInfo) {
  81403. return;
  81404. }
  81405. //harmonics now represent radiance
  81406. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81407. if (irradianceInfo.polynomials) {
  81408. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81409. }
  81410. else {
  81411. // convert From SH to SP.
  81412. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81413. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81414. }
  81415. };
  81416. /**
  81417. * Upload spherical polynomial coefficients to the texture
  81418. * @param polynmials Spherical polynmial coefficients (9)
  81419. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81420. */
  81421. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81422. outPolynomialCoefficents.x.x = polynmials.x[0];
  81423. outPolynomialCoefficents.x.y = polynmials.x[1];
  81424. outPolynomialCoefficents.x.z = polynmials.x[2];
  81425. outPolynomialCoefficents.y.x = polynmials.y[0];
  81426. outPolynomialCoefficents.y.y = polynmials.y[1];
  81427. outPolynomialCoefficents.y.z = polynmials.y[2];
  81428. outPolynomialCoefficents.z.x = polynmials.z[0];
  81429. outPolynomialCoefficents.z.y = polynmials.z[1];
  81430. outPolynomialCoefficents.z.z = polynmials.z[2];
  81431. //xx
  81432. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81433. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81434. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81435. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81436. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81437. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81438. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81439. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81440. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81441. //yz
  81442. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81443. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81444. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81445. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81446. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81447. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81448. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81449. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81450. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81451. };
  81452. /**
  81453. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81454. * L = (1/pi) * E * rho
  81455. *
  81456. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81457. * @param harmonics Spherical harmonic coefficients (9)
  81458. */
  81459. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81460. var scaleFactor = 1 / Math.PI;
  81461. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81462. // (The pixel shader must apply albedo after texture fetches, etc).
  81463. harmonics.l00[0] *= scaleFactor;
  81464. harmonics.l00[1] *= scaleFactor;
  81465. harmonics.l00[2] *= scaleFactor;
  81466. harmonics.l1_1[0] *= scaleFactor;
  81467. harmonics.l1_1[1] *= scaleFactor;
  81468. harmonics.l1_1[2] *= scaleFactor;
  81469. harmonics.l10[0] *= scaleFactor;
  81470. harmonics.l10[1] *= scaleFactor;
  81471. harmonics.l10[2] *= scaleFactor;
  81472. harmonics.l11[0] *= scaleFactor;
  81473. harmonics.l11[1] *= scaleFactor;
  81474. harmonics.l11[2] *= scaleFactor;
  81475. harmonics.l2_2[0] *= scaleFactor;
  81476. harmonics.l2_2[1] *= scaleFactor;
  81477. harmonics.l2_2[2] *= scaleFactor;
  81478. harmonics.l2_1[0] *= scaleFactor;
  81479. harmonics.l2_1[1] *= scaleFactor;
  81480. harmonics.l2_1[2] *= scaleFactor;
  81481. harmonics.l20[0] *= scaleFactor;
  81482. harmonics.l20[1] *= scaleFactor;
  81483. harmonics.l20[2] *= scaleFactor;
  81484. harmonics.l21[0] *= scaleFactor;
  81485. harmonics.l21[1] *= scaleFactor;
  81486. harmonics.l21[2] *= scaleFactor;
  81487. harmonics.l22[0] *= scaleFactor;
  81488. harmonics.l22[1] *= scaleFactor;
  81489. harmonics.l22[2] *= scaleFactor;
  81490. };
  81491. /**
  81492. * Convert spherical harmonics to spherical polynomial coefficients
  81493. * @param harmonics Spherical harmonic coefficients (9)
  81494. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81495. */
  81496. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81497. var rPi = 1 / Math.PI;
  81498. //x
  81499. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81500. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81501. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81502. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81503. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81504. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81505. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81506. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81507. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81508. //xx
  81509. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81510. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81511. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81512. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81513. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81514. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81515. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81516. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81517. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81518. //yz
  81519. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81520. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81521. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81522. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81523. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81524. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81525. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81526. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81527. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81528. };
  81529. /**
  81530. * Magic number identifying the env file.
  81531. */
  81532. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81533. return EnvironmentTextureTools;
  81534. }());
  81535. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81536. })(BABYLON || (BABYLON = {}));
  81537. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81538. var BABYLON;
  81539. (function (BABYLON) {
  81540. /**
  81541. * This represents a texture coming from an HDR input.
  81542. *
  81543. * The only supported format is currently panorama picture stored in RGBE format.
  81544. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81545. */
  81546. var HDRCubeTexture = /** @class */ (function (_super) {
  81547. __extends(HDRCubeTexture, _super);
  81548. /**
  81549. * Instantiates an HDRTexture from the following parameters.
  81550. *
  81551. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81552. * @param scene The scene the texture will be used in
  81553. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81554. * @param noMipmap Forces to not generate the mipmap if true
  81555. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81556. * @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)
  81557. * @param reserved Reserved flag for internal use.
  81558. */
  81559. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81560. if (noMipmap === void 0) { noMipmap = false; }
  81561. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81562. if (gammaSpace === void 0) { gammaSpace = false; }
  81563. if (reserved === void 0) { reserved = false; }
  81564. if (onLoad === void 0) { onLoad = null; }
  81565. if (onError === void 0) { onError = null; }
  81566. var _this = _super.call(this, scene) || this;
  81567. _this._generateHarmonics = true;
  81568. _this._onLoad = null;
  81569. _this._onError = null;
  81570. /**
  81571. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81572. */
  81573. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81574. _this._isBlocking = true;
  81575. _this._rotationY = 0;
  81576. /**
  81577. * Gets or sets the center of the bounding box associated with the cube texture
  81578. * It must define where the camera used to render the texture was set
  81579. */
  81580. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81581. if (!url) {
  81582. return _this;
  81583. }
  81584. _this.name = url;
  81585. _this.url = url;
  81586. _this.hasAlpha = false;
  81587. _this.isCube = true;
  81588. _this._textureMatrix = BABYLON.Matrix.Identity();
  81589. _this._onLoad = onLoad;
  81590. _this._onError = onError;
  81591. _this.gammaSpace = gammaSpace;
  81592. _this._noMipmap = noMipmap;
  81593. _this._size = size;
  81594. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81595. if (!_this._texture) {
  81596. if (!scene.useDelayedTextureLoading) {
  81597. _this.loadTexture();
  81598. }
  81599. else {
  81600. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81601. }
  81602. }
  81603. return _this;
  81604. }
  81605. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81606. /**
  81607. * Gets wether or not the texture is blocking during loading.
  81608. */
  81609. get: function () {
  81610. return this._isBlocking;
  81611. },
  81612. /**
  81613. * Sets wether or not the texture is blocking during loading.
  81614. */
  81615. set: function (value) {
  81616. this._isBlocking = value;
  81617. },
  81618. enumerable: true,
  81619. configurable: true
  81620. });
  81621. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81622. /**
  81623. * Gets texture matrix rotation angle around Y axis radians.
  81624. */
  81625. get: function () {
  81626. return this._rotationY;
  81627. },
  81628. /**
  81629. * Sets texture matrix rotation angle around Y axis in radians.
  81630. */
  81631. set: function (value) {
  81632. this._rotationY = value;
  81633. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81634. },
  81635. enumerable: true,
  81636. configurable: true
  81637. });
  81638. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81639. get: function () {
  81640. return this._boundingBoxSize;
  81641. },
  81642. /**
  81643. * Gets or sets the size of the bounding box associated with the cube texture
  81644. * When defined, the cubemap will switch to local mode
  81645. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81646. * @example https://www.babylonjs-playground.com/#RNASML
  81647. */
  81648. set: function (value) {
  81649. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81650. return;
  81651. }
  81652. this._boundingBoxSize = value;
  81653. var scene = this.getScene();
  81654. if (scene) {
  81655. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81656. }
  81657. },
  81658. enumerable: true,
  81659. configurable: true
  81660. });
  81661. /**
  81662. * Occurs when the file is raw .hdr file.
  81663. */
  81664. HDRCubeTexture.prototype.loadTexture = function () {
  81665. var _this = this;
  81666. var callback = function (buffer) {
  81667. _this.lodGenerationOffset = 0.0;
  81668. _this.lodGenerationScale = 0.8;
  81669. var scene = _this.getScene();
  81670. if (!scene) {
  81671. return null;
  81672. }
  81673. // Extract the raw linear data.
  81674. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81675. // Generate harmonics if needed.
  81676. if (_this._generateHarmonics) {
  81677. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81678. _this.sphericalPolynomial = sphericalPolynomial;
  81679. }
  81680. var results = [];
  81681. var byteArray = null;
  81682. // Push each faces.
  81683. for (var j = 0; j < 6; j++) {
  81684. // Create uintarray fallback.
  81685. if (!scene.getEngine().getCaps().textureFloat) {
  81686. // 3 channels of 1 bytes per pixel in bytes.
  81687. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81688. byteArray = new Uint8Array(byteBuffer);
  81689. }
  81690. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81691. // If special cases.
  81692. if (_this.gammaSpace || byteArray) {
  81693. for (var i = 0; i < _this._size * _this._size; i++) {
  81694. // Put in gamma space if requested.
  81695. if (_this.gammaSpace) {
  81696. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81697. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81698. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81699. }
  81700. // Convert to int texture for fallback.
  81701. if (byteArray) {
  81702. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81703. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81704. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81705. // May use luminance instead if the result is not accurate.
  81706. var max = Math.max(Math.max(r, g), b);
  81707. if (max > 255) {
  81708. var scale = 255 / max;
  81709. r *= scale;
  81710. g *= scale;
  81711. b *= scale;
  81712. }
  81713. byteArray[(i * 3) + 0] = r;
  81714. byteArray[(i * 3) + 1] = g;
  81715. byteArray[(i * 3) + 2] = b;
  81716. }
  81717. }
  81718. }
  81719. if (byteArray) {
  81720. results.push(byteArray);
  81721. }
  81722. else {
  81723. results.push(dataFace);
  81724. }
  81725. }
  81726. return results;
  81727. };
  81728. var scene = this.getScene();
  81729. if (scene) {
  81730. 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);
  81731. }
  81732. };
  81733. HDRCubeTexture.prototype.clone = function () {
  81734. var scene = this.getScene();
  81735. if (!scene) {
  81736. return this;
  81737. }
  81738. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81739. // Base texture
  81740. newTexture.level = this.level;
  81741. newTexture.wrapU = this.wrapU;
  81742. newTexture.wrapV = this.wrapV;
  81743. newTexture.coordinatesIndex = this.coordinatesIndex;
  81744. newTexture.coordinatesMode = this.coordinatesMode;
  81745. return newTexture;
  81746. };
  81747. // Methods
  81748. HDRCubeTexture.prototype.delayLoad = function () {
  81749. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81750. return;
  81751. }
  81752. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81753. this._texture = this._getFromCache(this.url, this._noMipmap);
  81754. if (!this._texture) {
  81755. this.loadTexture();
  81756. }
  81757. };
  81758. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81759. return this._textureMatrix;
  81760. };
  81761. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81762. this._textureMatrix = value;
  81763. };
  81764. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81765. var texture = null;
  81766. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81767. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81768. texture.name = parsedTexture.name;
  81769. texture.hasAlpha = parsedTexture.hasAlpha;
  81770. texture.level = parsedTexture.level;
  81771. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81772. texture.isBlocking = parsedTexture.isBlocking;
  81773. }
  81774. if (texture) {
  81775. if (parsedTexture.boundingBoxPosition) {
  81776. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81777. }
  81778. if (parsedTexture.boundingBoxSize) {
  81779. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81780. }
  81781. if (parsedTexture.rotationY) {
  81782. texture.rotationY = parsedTexture.rotationY;
  81783. }
  81784. }
  81785. return texture;
  81786. };
  81787. HDRCubeTexture.prototype.serialize = function () {
  81788. if (!this.name) {
  81789. return null;
  81790. }
  81791. var serializationObject = {};
  81792. serializationObject.name = this.name;
  81793. serializationObject.hasAlpha = this.hasAlpha;
  81794. serializationObject.isCube = true;
  81795. serializationObject.level = this.level;
  81796. serializationObject.size = this._size;
  81797. serializationObject.coordinatesMode = this.coordinatesMode;
  81798. serializationObject.useInGammaSpace = this.gammaSpace;
  81799. serializationObject.generateHarmonics = this._generateHarmonics;
  81800. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81801. serializationObject.noMipmap = this._noMipmap;
  81802. serializationObject.isBlocking = this._isBlocking;
  81803. serializationObject.rotationY = this._rotationY;
  81804. return serializationObject;
  81805. };
  81806. HDRCubeTexture._facesMapping = [
  81807. "right",
  81808. "left",
  81809. "up",
  81810. "down",
  81811. "front",
  81812. "back"
  81813. ];
  81814. return HDRCubeTexture;
  81815. }(BABYLON.BaseTexture));
  81816. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81817. })(BABYLON || (BABYLON = {}));
  81818. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81819. var BABYLON;
  81820. (function (BABYLON) {
  81821. var IndexedVector2 = /** @class */ (function (_super) {
  81822. __extends(IndexedVector2, _super);
  81823. function IndexedVector2(original, index) {
  81824. var _this = _super.call(this, original.x, original.y) || this;
  81825. _this.index = index;
  81826. return _this;
  81827. }
  81828. return IndexedVector2;
  81829. }(BABYLON.Vector2));
  81830. var PolygonPoints = /** @class */ (function () {
  81831. function PolygonPoints() {
  81832. this.elements = new Array();
  81833. }
  81834. PolygonPoints.prototype.add = function (originalPoints) {
  81835. var _this = this;
  81836. var result = new Array();
  81837. originalPoints.forEach(function (point) {
  81838. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81839. var newPoint = new IndexedVector2(point, _this.elements.length);
  81840. result.push(newPoint);
  81841. _this.elements.push(newPoint);
  81842. }
  81843. });
  81844. return result;
  81845. };
  81846. PolygonPoints.prototype.computeBounds = function () {
  81847. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81848. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81849. this.elements.forEach(function (point) {
  81850. // x
  81851. if (point.x < lmin.x) {
  81852. lmin.x = point.x;
  81853. }
  81854. else if (point.x > lmax.x) {
  81855. lmax.x = point.x;
  81856. }
  81857. // y
  81858. if (point.y < lmin.y) {
  81859. lmin.y = point.y;
  81860. }
  81861. else if (point.y > lmax.y) {
  81862. lmax.y = point.y;
  81863. }
  81864. });
  81865. return {
  81866. min: lmin,
  81867. max: lmax,
  81868. width: lmax.x - lmin.x,
  81869. height: lmax.y - lmin.y
  81870. };
  81871. };
  81872. return PolygonPoints;
  81873. }());
  81874. var Polygon = /** @class */ (function () {
  81875. function Polygon() {
  81876. }
  81877. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81878. return [
  81879. new BABYLON.Vector2(xmin, ymin),
  81880. new BABYLON.Vector2(xmax, ymin),
  81881. new BABYLON.Vector2(xmax, ymax),
  81882. new BABYLON.Vector2(xmin, ymax)
  81883. ];
  81884. };
  81885. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81886. if (cx === void 0) { cx = 0; }
  81887. if (cy === void 0) { cy = 0; }
  81888. if (numberOfSides === void 0) { numberOfSides = 32; }
  81889. var result = new Array();
  81890. var angle = 0;
  81891. var increment = (Math.PI * 2) / numberOfSides;
  81892. for (var i = 0; i < numberOfSides; i++) {
  81893. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81894. angle -= increment;
  81895. }
  81896. return result;
  81897. };
  81898. Polygon.Parse = function (input) {
  81899. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81900. var i, result = [];
  81901. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81902. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81903. }
  81904. return result;
  81905. };
  81906. Polygon.StartingAt = function (x, y) {
  81907. return BABYLON.Path2.StartingAt(x, y);
  81908. };
  81909. return Polygon;
  81910. }());
  81911. BABYLON.Polygon = Polygon;
  81912. var PolygonMeshBuilder = /** @class */ (function () {
  81913. function PolygonMeshBuilder(name, contours, scene) {
  81914. this._points = new PolygonPoints();
  81915. this._outlinepoints = new PolygonPoints();
  81916. this._holes = new Array();
  81917. this._epoints = new Array();
  81918. this._eholes = new Array();
  81919. this._name = name;
  81920. this._scene = scene;
  81921. var points;
  81922. if (contours instanceof BABYLON.Path2) {
  81923. points = contours.getPoints();
  81924. }
  81925. else {
  81926. points = contours;
  81927. }
  81928. this._addToepoint(points);
  81929. this._points.add(points);
  81930. this._outlinepoints.add(points);
  81931. if (typeof earcut === 'undefined') {
  81932. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81933. }
  81934. }
  81935. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81936. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81937. var p = points_1[_i];
  81938. this._epoints.push(p.x, p.y);
  81939. }
  81940. };
  81941. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81942. this._points.add(hole);
  81943. var holepoints = new PolygonPoints();
  81944. holepoints.add(hole);
  81945. this._holes.push(holepoints);
  81946. this._eholes.push(this._epoints.length / 2);
  81947. this._addToepoint(hole);
  81948. return this;
  81949. };
  81950. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81951. var _this = this;
  81952. if (updatable === void 0) { updatable = false; }
  81953. if (depth === void 0) { depth = 0; }
  81954. var result = new BABYLON.Mesh(this._name, this._scene);
  81955. var normals = new Array();
  81956. var positions = new Array();
  81957. var uvs = new Array();
  81958. var bounds = this._points.computeBounds();
  81959. this._points.elements.forEach(function (p) {
  81960. normals.push(0, 1.0, 0);
  81961. positions.push(p.x, 0, p.y);
  81962. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81963. });
  81964. var indices = new Array();
  81965. var res = earcut(this._epoints, this._eholes, 2);
  81966. for (var i = 0; i < res.length; i++) {
  81967. indices.push(res[i]);
  81968. }
  81969. if (depth > 0) {
  81970. var positionscount = (positions.length / 3); //get the current pointcount
  81971. this._points.elements.forEach(function (p) {
  81972. normals.push(0, -1.0, 0);
  81973. positions.push(p.x, -depth, p.y);
  81974. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81975. });
  81976. var totalCount = indices.length;
  81977. for (var i = 0; i < totalCount; i += 3) {
  81978. var i0 = indices[i + 0];
  81979. var i1 = indices[i + 1];
  81980. var i2 = indices[i + 2];
  81981. indices.push(i2 + positionscount);
  81982. indices.push(i1 + positionscount);
  81983. indices.push(i0 + positionscount);
  81984. }
  81985. //Add the sides
  81986. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81987. this._holes.forEach(function (hole) {
  81988. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81989. });
  81990. }
  81991. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81992. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81993. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81994. result.setIndices(indices);
  81995. return result;
  81996. };
  81997. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81998. var StartIndex = positions.length / 3;
  81999. var ulength = 0;
  82000. for (var i = 0; i < points.elements.length; i++) {
  82001. var p = points.elements[i];
  82002. var p1;
  82003. if ((i + 1) > points.elements.length - 1) {
  82004. p1 = points.elements[0];
  82005. }
  82006. else {
  82007. p1 = points.elements[i + 1];
  82008. }
  82009. positions.push(p.x, 0, p.y);
  82010. positions.push(p.x, -depth, p.y);
  82011. positions.push(p1.x, 0, p1.y);
  82012. positions.push(p1.x, -depth, p1.y);
  82013. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82014. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82015. var v3 = v2.subtract(v1);
  82016. var v4 = new BABYLON.Vector3(0, 1, 0);
  82017. var vn = BABYLON.Vector3.Cross(v3, v4);
  82018. vn = vn.normalize();
  82019. uvs.push(ulength / bounds.width, 0);
  82020. uvs.push(ulength / bounds.width, 1);
  82021. ulength += v3.length();
  82022. uvs.push((ulength / bounds.width), 0);
  82023. uvs.push((ulength / bounds.width), 1);
  82024. if (!flip) {
  82025. normals.push(-vn.x, -vn.y, -vn.z);
  82026. normals.push(-vn.x, -vn.y, -vn.z);
  82027. normals.push(-vn.x, -vn.y, -vn.z);
  82028. normals.push(-vn.x, -vn.y, -vn.z);
  82029. indices.push(StartIndex);
  82030. indices.push(StartIndex + 1);
  82031. indices.push(StartIndex + 2);
  82032. indices.push(StartIndex + 1);
  82033. indices.push(StartIndex + 3);
  82034. indices.push(StartIndex + 2);
  82035. }
  82036. else {
  82037. normals.push(vn.x, vn.y, vn.z);
  82038. normals.push(vn.x, vn.y, vn.z);
  82039. normals.push(vn.x, vn.y, vn.z);
  82040. normals.push(vn.x, vn.y, vn.z);
  82041. indices.push(StartIndex);
  82042. indices.push(StartIndex + 2);
  82043. indices.push(StartIndex + 1);
  82044. indices.push(StartIndex + 1);
  82045. indices.push(StartIndex + 2);
  82046. indices.push(StartIndex + 3);
  82047. }
  82048. StartIndex += 4;
  82049. }
  82050. ;
  82051. };
  82052. return PolygonMeshBuilder;
  82053. }());
  82054. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82055. })(BABYLON || (BABYLON = {}));
  82056. //# sourceMappingURL=babylon.polygonMesh.js.map
  82057. var BABYLON;
  82058. (function (BABYLON) {
  82059. // Unique ID when we import meshes from Babylon to CSG
  82060. var currentCSGMeshId = 0;
  82061. // # class Vertex
  82062. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82063. // one to provide additional features like texture coordinates and vertex
  82064. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82065. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82066. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82067. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82068. // is not used anywhere else.
  82069. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82070. var Vertex = /** @class */ (function () {
  82071. function Vertex(pos, normal, uv) {
  82072. this.pos = pos;
  82073. this.normal = normal;
  82074. this.uv = uv;
  82075. }
  82076. Vertex.prototype.clone = function () {
  82077. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82078. };
  82079. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82080. // orientation of a polygon is flipped.
  82081. Vertex.prototype.flip = function () {
  82082. this.normal = this.normal.scale(-1);
  82083. };
  82084. // Create a new vertex between this vertex and `other` by linearly
  82085. // interpolating all properties using a parameter of `t`. Subclasses should
  82086. // override this to interpolate additional properties.
  82087. Vertex.prototype.interpolate = function (other, t) {
  82088. 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));
  82089. };
  82090. return Vertex;
  82091. }());
  82092. // # class Plane
  82093. // Represents a plane in 3D space.
  82094. var Plane = /** @class */ (function () {
  82095. function Plane(normal, w) {
  82096. this.normal = normal;
  82097. this.w = w;
  82098. }
  82099. Plane.FromPoints = function (a, b, c) {
  82100. var v0 = c.subtract(a);
  82101. var v1 = b.subtract(a);
  82102. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82103. return null;
  82104. }
  82105. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82106. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82107. };
  82108. Plane.prototype.clone = function () {
  82109. return new Plane(this.normal.clone(), this.w);
  82110. };
  82111. Plane.prototype.flip = function () {
  82112. this.normal.scaleInPlace(-1);
  82113. this.w = -this.w;
  82114. };
  82115. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82116. // fragments in the appropriate lists. Coplanar polygons go into either
  82117. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82118. // respect to this plane. Polygons in front or in back of this plane go into
  82119. // either `front` or `back`.
  82120. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82121. var COPLANAR = 0;
  82122. var FRONT = 1;
  82123. var BACK = 2;
  82124. var SPANNING = 3;
  82125. // Classify each point as well as the entire polygon into one of the above
  82126. // four classes.
  82127. var polygonType = 0;
  82128. var types = [];
  82129. var i;
  82130. var t;
  82131. for (i = 0; i < polygon.vertices.length; i++) {
  82132. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82133. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82134. polygonType |= type;
  82135. types.push(type);
  82136. }
  82137. // Put the polygon in the correct list, splitting it when necessary.
  82138. switch (polygonType) {
  82139. case COPLANAR:
  82140. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82141. break;
  82142. case FRONT:
  82143. front.push(polygon);
  82144. break;
  82145. case BACK:
  82146. back.push(polygon);
  82147. break;
  82148. case SPANNING:
  82149. var f = [], b = [];
  82150. for (i = 0; i < polygon.vertices.length; i++) {
  82151. var j = (i + 1) % polygon.vertices.length;
  82152. var ti = types[i], tj = types[j];
  82153. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82154. if (ti !== BACK)
  82155. f.push(vi);
  82156. if (ti !== FRONT)
  82157. b.push(ti !== BACK ? vi.clone() : vi);
  82158. if ((ti | tj) === SPANNING) {
  82159. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82160. var v = vi.interpolate(vj, t);
  82161. f.push(v);
  82162. b.push(v.clone());
  82163. }
  82164. }
  82165. var poly;
  82166. if (f.length >= 3) {
  82167. poly = new Polygon(f, polygon.shared);
  82168. if (poly.plane)
  82169. front.push(poly);
  82170. }
  82171. if (b.length >= 3) {
  82172. poly = new Polygon(b, polygon.shared);
  82173. if (poly.plane)
  82174. back.push(poly);
  82175. }
  82176. break;
  82177. }
  82178. };
  82179. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82180. // point is on the plane.
  82181. Plane.EPSILON = 1e-5;
  82182. return Plane;
  82183. }());
  82184. // # class Polygon
  82185. // Represents a convex polygon. The vertices used to initialize a polygon must
  82186. // be coplanar and form a convex loop.
  82187. //
  82188. // Each convex polygon has a `shared` property, which is shared between all
  82189. // polygons that are clones of each other or were split from the same polygon.
  82190. // This can be used to define per-polygon properties (such as surface color).
  82191. var Polygon = /** @class */ (function () {
  82192. function Polygon(vertices, shared) {
  82193. this.vertices = vertices;
  82194. this.shared = shared;
  82195. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82196. }
  82197. Polygon.prototype.clone = function () {
  82198. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82199. return new Polygon(vertices, this.shared);
  82200. };
  82201. Polygon.prototype.flip = function () {
  82202. this.vertices.reverse().map(function (v) { v.flip(); });
  82203. this.plane.flip();
  82204. };
  82205. return Polygon;
  82206. }());
  82207. // # class Node
  82208. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82209. // by picking a polygon to split along. That polygon (and all other coplanar
  82210. // polygons) are added directly to that node and the other polygons are added to
  82211. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82212. // no distinction between internal and leaf nodes.
  82213. var Node = /** @class */ (function () {
  82214. function Node(polygons) {
  82215. this.plane = null;
  82216. this.front = null;
  82217. this.back = null;
  82218. this.polygons = new Array();
  82219. if (polygons) {
  82220. this.build(polygons);
  82221. }
  82222. }
  82223. Node.prototype.clone = function () {
  82224. var node = new Node();
  82225. node.plane = this.plane && this.plane.clone();
  82226. node.front = this.front && this.front.clone();
  82227. node.back = this.back && this.back.clone();
  82228. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82229. return node;
  82230. };
  82231. // Convert solid space to empty space and empty space to solid space.
  82232. Node.prototype.invert = function () {
  82233. for (var i = 0; i < this.polygons.length; i++) {
  82234. this.polygons[i].flip();
  82235. }
  82236. if (this.plane) {
  82237. this.plane.flip();
  82238. }
  82239. if (this.front) {
  82240. this.front.invert();
  82241. }
  82242. if (this.back) {
  82243. this.back.invert();
  82244. }
  82245. var temp = this.front;
  82246. this.front = this.back;
  82247. this.back = temp;
  82248. };
  82249. // Recursively remove all polygons in `polygons` that are inside this BSP
  82250. // tree.
  82251. Node.prototype.clipPolygons = function (polygons) {
  82252. if (!this.plane)
  82253. return polygons.slice();
  82254. var front = new Array(), back = new Array();
  82255. for (var i = 0; i < polygons.length; i++) {
  82256. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82257. }
  82258. if (this.front) {
  82259. front = this.front.clipPolygons(front);
  82260. }
  82261. if (this.back) {
  82262. back = this.back.clipPolygons(back);
  82263. }
  82264. else {
  82265. back = [];
  82266. }
  82267. return front.concat(back);
  82268. };
  82269. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82270. // `bsp`.
  82271. Node.prototype.clipTo = function (bsp) {
  82272. this.polygons = bsp.clipPolygons(this.polygons);
  82273. if (this.front)
  82274. this.front.clipTo(bsp);
  82275. if (this.back)
  82276. this.back.clipTo(bsp);
  82277. };
  82278. // Return a list of all polygons in this BSP tree.
  82279. Node.prototype.allPolygons = function () {
  82280. var polygons = this.polygons.slice();
  82281. if (this.front)
  82282. polygons = polygons.concat(this.front.allPolygons());
  82283. if (this.back)
  82284. polygons = polygons.concat(this.back.allPolygons());
  82285. return polygons;
  82286. };
  82287. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82288. // new polygons are filtered down to the bottom of the tree and become new
  82289. // nodes there. Each set of polygons is partitioned using the first polygon
  82290. // (no heuristic is used to pick a good split).
  82291. Node.prototype.build = function (polygons) {
  82292. if (!polygons.length)
  82293. return;
  82294. if (!this.plane)
  82295. this.plane = polygons[0].plane.clone();
  82296. var front = new Array(), back = new Array();
  82297. for (var i = 0; i < polygons.length; i++) {
  82298. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82299. }
  82300. if (front.length) {
  82301. if (!this.front)
  82302. this.front = new Node();
  82303. this.front.build(front);
  82304. }
  82305. if (back.length) {
  82306. if (!this.back)
  82307. this.back = new Node();
  82308. this.back.build(back);
  82309. }
  82310. };
  82311. return Node;
  82312. }());
  82313. var CSG = /** @class */ (function () {
  82314. function CSG() {
  82315. this.polygons = new Array();
  82316. }
  82317. // Convert BABYLON.Mesh to BABYLON.CSG
  82318. CSG.FromMesh = function (mesh) {
  82319. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82320. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82321. if (mesh instanceof BABYLON.Mesh) {
  82322. mesh.computeWorldMatrix(true);
  82323. matrix = mesh.getWorldMatrix();
  82324. meshPosition = mesh.position.clone();
  82325. meshRotation = mesh.rotation.clone();
  82326. if (mesh.rotationQuaternion) {
  82327. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82328. }
  82329. meshScaling = mesh.scaling.clone();
  82330. }
  82331. else {
  82332. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82333. }
  82334. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82335. var subMeshes = mesh.subMeshes;
  82336. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82337. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82338. vertices = [];
  82339. for (var j = 0; j < 3; j++) {
  82340. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82341. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82342. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82343. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82344. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82345. vertex = new Vertex(position, normal, uv);
  82346. vertices.push(vertex);
  82347. }
  82348. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82349. // To handle the case of degenerated triangle
  82350. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82351. if (polygon.plane)
  82352. polygons.push(polygon);
  82353. }
  82354. }
  82355. var csg = CSG.FromPolygons(polygons);
  82356. csg.matrix = matrix;
  82357. csg.position = meshPosition;
  82358. csg.rotation = meshRotation;
  82359. csg.scaling = meshScaling;
  82360. csg.rotationQuaternion = meshRotationQuaternion;
  82361. currentCSGMeshId++;
  82362. return csg;
  82363. };
  82364. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82365. CSG.FromPolygons = function (polygons) {
  82366. var csg = new CSG();
  82367. csg.polygons = polygons;
  82368. return csg;
  82369. };
  82370. CSG.prototype.clone = function () {
  82371. var csg = new CSG();
  82372. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82373. csg.copyTransformAttributes(this);
  82374. return csg;
  82375. };
  82376. CSG.prototype.union = function (csg) {
  82377. var a = new Node(this.clone().polygons);
  82378. var b = new Node(csg.clone().polygons);
  82379. a.clipTo(b);
  82380. b.clipTo(a);
  82381. b.invert();
  82382. b.clipTo(a);
  82383. b.invert();
  82384. a.build(b.allPolygons());
  82385. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82386. };
  82387. CSG.prototype.unionInPlace = function (csg) {
  82388. var a = new Node(this.polygons);
  82389. var b = new Node(csg.polygons);
  82390. a.clipTo(b);
  82391. b.clipTo(a);
  82392. b.invert();
  82393. b.clipTo(a);
  82394. b.invert();
  82395. a.build(b.allPolygons());
  82396. this.polygons = a.allPolygons();
  82397. };
  82398. CSG.prototype.subtract = function (csg) {
  82399. var a = new Node(this.clone().polygons);
  82400. var b = new Node(csg.clone().polygons);
  82401. a.invert();
  82402. a.clipTo(b);
  82403. b.clipTo(a);
  82404. b.invert();
  82405. b.clipTo(a);
  82406. b.invert();
  82407. a.build(b.allPolygons());
  82408. a.invert();
  82409. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82410. };
  82411. CSG.prototype.subtractInPlace = function (csg) {
  82412. var a = new Node(this.polygons);
  82413. var b = new Node(csg.polygons);
  82414. a.invert();
  82415. a.clipTo(b);
  82416. b.clipTo(a);
  82417. b.invert();
  82418. b.clipTo(a);
  82419. b.invert();
  82420. a.build(b.allPolygons());
  82421. a.invert();
  82422. this.polygons = a.allPolygons();
  82423. };
  82424. CSG.prototype.intersect = function (csg) {
  82425. var a = new Node(this.clone().polygons);
  82426. var b = new Node(csg.clone().polygons);
  82427. a.invert();
  82428. b.clipTo(a);
  82429. b.invert();
  82430. a.clipTo(b);
  82431. b.clipTo(a);
  82432. a.build(b.allPolygons());
  82433. a.invert();
  82434. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82435. };
  82436. CSG.prototype.intersectInPlace = function (csg) {
  82437. var a = new Node(this.polygons);
  82438. var b = new Node(csg.polygons);
  82439. a.invert();
  82440. b.clipTo(a);
  82441. b.invert();
  82442. a.clipTo(b);
  82443. b.clipTo(a);
  82444. a.build(b.allPolygons());
  82445. a.invert();
  82446. this.polygons = a.allPolygons();
  82447. };
  82448. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82449. // not modified.
  82450. CSG.prototype.inverse = function () {
  82451. var csg = this.clone();
  82452. csg.inverseInPlace();
  82453. return csg;
  82454. };
  82455. CSG.prototype.inverseInPlace = function () {
  82456. this.polygons.map(function (p) { p.flip(); });
  82457. };
  82458. // This is used to keep meshes transformations so they can be restored
  82459. // when we build back a Babylon Mesh
  82460. // NB : All CSG operations are performed in world coordinates
  82461. CSG.prototype.copyTransformAttributes = function (csg) {
  82462. this.matrix = csg.matrix;
  82463. this.position = csg.position;
  82464. this.rotation = csg.rotation;
  82465. this.scaling = csg.scaling;
  82466. this.rotationQuaternion = csg.rotationQuaternion;
  82467. return this;
  82468. };
  82469. // Build Raw mesh from CSG
  82470. // Coordinates here are in world space
  82471. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82472. var matrix = this.matrix.clone();
  82473. matrix.invert();
  82474. 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;
  82475. if (keepSubMeshes) {
  82476. // Sort Polygons, since subMeshes are indices range
  82477. polygons.sort(function (a, b) {
  82478. if (a.shared.meshId === b.shared.meshId) {
  82479. return a.shared.subMeshId - b.shared.subMeshId;
  82480. }
  82481. else {
  82482. return a.shared.meshId - b.shared.meshId;
  82483. }
  82484. });
  82485. }
  82486. for (var i = 0, il = polygons.length; i < il; i++) {
  82487. polygon = polygons[i];
  82488. // Building SubMeshes
  82489. if (!subMesh_dict[polygon.shared.meshId]) {
  82490. subMesh_dict[polygon.shared.meshId] = {};
  82491. }
  82492. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82493. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82494. indexStart: +Infinity,
  82495. indexEnd: -Infinity,
  82496. materialIndex: polygon.shared.materialIndex
  82497. };
  82498. }
  82499. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82500. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82501. polygonIndices[0] = 0;
  82502. polygonIndices[1] = j - 1;
  82503. polygonIndices[2] = j;
  82504. for (var k = 0; k < 3; k++) {
  82505. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82506. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82507. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82508. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82509. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82510. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82511. // Check if 2 points can be merged
  82512. if (!(typeof vertex_idx !== 'undefined' &&
  82513. normals[vertex_idx * 3] === localNormal.x &&
  82514. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82515. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82516. uvs[vertex_idx * 2] === uv.x &&
  82517. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82518. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82519. uvs.push(uv.x, uv.y);
  82520. normals.push(normal.x, normal.y, normal.z);
  82521. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82522. }
  82523. indices.push(vertex_idx);
  82524. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82525. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82526. currentIndex++;
  82527. }
  82528. }
  82529. }
  82530. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82531. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82532. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82533. mesh.setIndices(indices, null);
  82534. if (keepSubMeshes) {
  82535. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82536. var materialIndexOffset = 0, materialMaxIndex;
  82537. mesh.subMeshes = new Array();
  82538. for (var m in subMesh_dict) {
  82539. materialMaxIndex = -1;
  82540. for (var sm in subMesh_dict[m]) {
  82541. subMesh_obj = subMesh_dict[m][sm];
  82542. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82543. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82544. }
  82545. materialIndexOffset += ++materialMaxIndex;
  82546. }
  82547. }
  82548. return mesh;
  82549. };
  82550. // Build Mesh from CSG taking material and transforms into account
  82551. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82552. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82553. mesh.material = material;
  82554. mesh.position.copyFrom(this.position);
  82555. mesh.rotation.copyFrom(this.rotation);
  82556. if (this.rotationQuaternion) {
  82557. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82558. }
  82559. mesh.scaling.copyFrom(this.scaling);
  82560. mesh.computeWorldMatrix(true);
  82561. return mesh;
  82562. };
  82563. return CSG;
  82564. }());
  82565. BABYLON.CSG = CSG;
  82566. })(BABYLON || (BABYLON = {}));
  82567. //# sourceMappingURL=babylon.csg.js.map
  82568. var BABYLON;
  82569. (function (BABYLON) {
  82570. var LensFlare = /** @class */ (function () {
  82571. function LensFlare(size, position, color, imgUrl, system) {
  82572. this.size = size;
  82573. this.position = position;
  82574. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82575. this.color = color || new BABYLON.Color3(1, 1, 1);
  82576. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82577. this._system = system;
  82578. system.lensFlares.push(this);
  82579. }
  82580. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82581. return new LensFlare(size, position, color, imgUrl, system);
  82582. };
  82583. LensFlare.prototype.dispose = function () {
  82584. if (this.texture) {
  82585. this.texture.dispose();
  82586. }
  82587. // Remove from scene
  82588. var index = this._system.lensFlares.indexOf(this);
  82589. this._system.lensFlares.splice(index, 1);
  82590. };
  82591. ;
  82592. return LensFlare;
  82593. }());
  82594. BABYLON.LensFlare = LensFlare;
  82595. })(BABYLON || (BABYLON = {}));
  82596. //# sourceMappingURL=babylon.lensFlare.js.map
  82597. var BABYLON;
  82598. (function (BABYLON) {
  82599. var LensFlareSystem = /** @class */ (function () {
  82600. function LensFlareSystem(name, emitter, scene) {
  82601. this.name = name;
  82602. this.lensFlares = new Array();
  82603. this.borderLimit = 300;
  82604. this.viewportBorder = 0;
  82605. this.layerMask = 0x0FFFFFFF;
  82606. this._vertexBuffers = {};
  82607. this._isEnabled = true;
  82608. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82609. this._emitter = emitter;
  82610. this.id = name;
  82611. scene.lensFlareSystems.push(this);
  82612. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82613. var engine = scene.getEngine();
  82614. // VBO
  82615. var vertices = [];
  82616. vertices.push(1, 1);
  82617. vertices.push(-1, 1);
  82618. vertices.push(-1, -1);
  82619. vertices.push(1, -1);
  82620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82621. // Indices
  82622. var indices = [];
  82623. indices.push(0);
  82624. indices.push(1);
  82625. indices.push(2);
  82626. indices.push(0);
  82627. indices.push(2);
  82628. indices.push(3);
  82629. this._indexBuffer = engine.createIndexBuffer(indices);
  82630. // Effects
  82631. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82632. }
  82633. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82634. get: function () {
  82635. return this._isEnabled;
  82636. },
  82637. set: function (value) {
  82638. this._isEnabled = value;
  82639. },
  82640. enumerable: true,
  82641. configurable: true
  82642. });
  82643. LensFlareSystem.prototype.getScene = function () {
  82644. return this._scene;
  82645. };
  82646. LensFlareSystem.prototype.getEmitter = function () {
  82647. return this._emitter;
  82648. };
  82649. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82650. this._emitter = newEmitter;
  82651. };
  82652. LensFlareSystem.prototype.getEmitterPosition = function () {
  82653. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82654. };
  82655. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82656. var position = this.getEmitterPosition();
  82657. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82658. this._positionX = position.x;
  82659. this._positionY = position.y;
  82660. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82661. if (this.viewportBorder > 0) {
  82662. globalViewport.x -= this.viewportBorder;
  82663. globalViewport.y -= this.viewportBorder;
  82664. globalViewport.width += this.viewportBorder * 2;
  82665. globalViewport.height += this.viewportBorder * 2;
  82666. position.x += this.viewportBorder;
  82667. position.y += this.viewportBorder;
  82668. this._positionX += this.viewportBorder;
  82669. this._positionY += this.viewportBorder;
  82670. }
  82671. if (position.z > 0) {
  82672. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82673. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82674. return true;
  82675. }
  82676. return true;
  82677. }
  82678. return false;
  82679. };
  82680. LensFlareSystem.prototype._isVisible = function () {
  82681. if (!this._isEnabled || !this._scene.activeCamera) {
  82682. return false;
  82683. }
  82684. var emitterPosition = this.getEmitterPosition();
  82685. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82686. var distance = direction.length();
  82687. direction.normalize();
  82688. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82689. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82690. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82691. };
  82692. LensFlareSystem.prototype.render = function () {
  82693. if (!this._effect.isReady() || !this._scene.activeCamera)
  82694. return false;
  82695. var engine = this._scene.getEngine();
  82696. var viewport = this._scene.activeCamera.viewport;
  82697. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82698. // Position
  82699. if (!this.computeEffectivePosition(globalViewport)) {
  82700. return false;
  82701. }
  82702. // Visibility
  82703. if (!this._isVisible()) {
  82704. return false;
  82705. }
  82706. // Intensity
  82707. var awayX;
  82708. var awayY;
  82709. if (this._positionX < this.borderLimit + globalViewport.x) {
  82710. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82711. }
  82712. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82713. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82714. }
  82715. else {
  82716. awayX = 0;
  82717. }
  82718. if (this._positionY < this.borderLimit + globalViewport.y) {
  82719. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82720. }
  82721. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82722. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82723. }
  82724. else {
  82725. awayY = 0;
  82726. }
  82727. var away = (awayX > awayY) ? awayX : awayY;
  82728. away -= this.viewportBorder;
  82729. if (away > this.borderLimit) {
  82730. away = this.borderLimit;
  82731. }
  82732. var intensity = 1.0 - (away / this.borderLimit);
  82733. if (intensity < 0) {
  82734. return false;
  82735. }
  82736. if (intensity > 1.0) {
  82737. intensity = 1.0;
  82738. }
  82739. if (this.viewportBorder > 0) {
  82740. globalViewport.x += this.viewportBorder;
  82741. globalViewport.y += this.viewportBorder;
  82742. globalViewport.width -= this.viewportBorder * 2;
  82743. globalViewport.height -= this.viewportBorder * 2;
  82744. this._positionX -= this.viewportBorder;
  82745. this._positionY -= this.viewportBorder;
  82746. }
  82747. // Position
  82748. var centerX = globalViewport.x + globalViewport.width / 2;
  82749. var centerY = globalViewport.y + globalViewport.height / 2;
  82750. var distX = centerX - this._positionX;
  82751. var distY = centerY - this._positionY;
  82752. // Effects
  82753. engine.enableEffect(this._effect);
  82754. engine.setState(false);
  82755. engine.setDepthBuffer(false);
  82756. // VBOs
  82757. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82758. // Flares
  82759. for (var index = 0; index < this.lensFlares.length; index++) {
  82760. var flare = this.lensFlares[index];
  82761. engine.setAlphaMode(flare.alphaMode);
  82762. var x = centerX - (distX * flare.position);
  82763. var y = centerY - (distY * flare.position);
  82764. var cw = flare.size;
  82765. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82766. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82767. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82768. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82769. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82770. // Texture
  82771. this._effect.setTexture("textureSampler", flare.texture);
  82772. // Color
  82773. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82774. // Draw order
  82775. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82776. }
  82777. engine.setDepthBuffer(true);
  82778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82779. return true;
  82780. };
  82781. LensFlareSystem.prototype.dispose = function () {
  82782. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82783. if (vertexBuffer) {
  82784. vertexBuffer.dispose();
  82785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82786. }
  82787. if (this._indexBuffer) {
  82788. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82789. this._indexBuffer = null;
  82790. }
  82791. while (this.lensFlares.length) {
  82792. this.lensFlares[0].dispose();
  82793. }
  82794. // Remove from scene
  82795. var index = this._scene.lensFlareSystems.indexOf(this);
  82796. this._scene.lensFlareSystems.splice(index, 1);
  82797. };
  82798. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82799. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82800. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82801. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82802. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82803. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82804. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82805. var parsedFlare = parsedLensFlareSystem.flares[index];
  82806. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82807. }
  82808. return lensFlareSystem;
  82809. };
  82810. LensFlareSystem.prototype.serialize = function () {
  82811. var serializationObject = {};
  82812. serializationObject.id = this.id;
  82813. serializationObject.name = this.name;
  82814. serializationObject.emitterId = this.getEmitter().id;
  82815. serializationObject.borderLimit = this.borderLimit;
  82816. serializationObject.flares = [];
  82817. for (var index = 0; index < this.lensFlares.length; index++) {
  82818. var flare = this.lensFlares[index];
  82819. serializationObject.flares.push({
  82820. size: flare.size,
  82821. position: flare.position,
  82822. color: flare.color.asArray(),
  82823. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82824. });
  82825. }
  82826. return serializationObject;
  82827. };
  82828. return LensFlareSystem;
  82829. }());
  82830. BABYLON.LensFlareSystem = LensFlareSystem;
  82831. })(BABYLON || (BABYLON = {}));
  82832. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82833. var BABYLON;
  82834. (function (BABYLON) {
  82835. /**
  82836. * This is a holder class for the physics joint created by the physics plugin.
  82837. * It holds a set of functions to control the underlying joint.
  82838. */
  82839. var PhysicsJoint = /** @class */ (function () {
  82840. function PhysicsJoint(type, jointData) {
  82841. this.type = type;
  82842. this.jointData = jointData;
  82843. jointData.nativeParams = jointData.nativeParams || {};
  82844. }
  82845. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82846. get: function () {
  82847. return this._physicsJoint;
  82848. },
  82849. set: function (newJoint) {
  82850. if (this._physicsJoint) {
  82851. //remove from the wolrd
  82852. }
  82853. this._physicsJoint = newJoint;
  82854. },
  82855. enumerable: true,
  82856. configurable: true
  82857. });
  82858. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82859. set: function (physicsPlugin) {
  82860. this._physicsPlugin = physicsPlugin;
  82861. },
  82862. enumerable: true,
  82863. configurable: true
  82864. });
  82865. /**
  82866. * Execute a function that is physics-plugin specific.
  82867. * @param {Function} func the function that will be executed.
  82868. * It accepts two parameters: the physics world and the physics joint.
  82869. */
  82870. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82871. func(this._physicsPlugin.world, this._physicsJoint);
  82872. };
  82873. //TODO check if the native joints are the same
  82874. //Joint Types
  82875. PhysicsJoint.DistanceJoint = 0;
  82876. PhysicsJoint.HingeJoint = 1;
  82877. PhysicsJoint.BallAndSocketJoint = 2;
  82878. PhysicsJoint.WheelJoint = 3;
  82879. PhysicsJoint.SliderJoint = 4;
  82880. //OIMO
  82881. PhysicsJoint.PrismaticJoint = 5;
  82882. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82883. PhysicsJoint.UniversalJoint = 6;
  82884. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82885. //Cannon
  82886. //Similar to a Ball-Joint. Different in params
  82887. PhysicsJoint.PointToPointJoint = 8;
  82888. //Cannon only at the moment
  82889. PhysicsJoint.SpringJoint = 9;
  82890. PhysicsJoint.LockJoint = 10;
  82891. return PhysicsJoint;
  82892. }());
  82893. BABYLON.PhysicsJoint = PhysicsJoint;
  82894. /**
  82895. * A class representing a physics distance joint.
  82896. */
  82897. var DistanceJoint = /** @class */ (function (_super) {
  82898. __extends(DistanceJoint, _super);
  82899. function DistanceJoint(jointData) {
  82900. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82901. }
  82902. /**
  82903. * Update the predefined distance.
  82904. */
  82905. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82906. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82907. };
  82908. return DistanceJoint;
  82909. }(PhysicsJoint));
  82910. BABYLON.DistanceJoint = DistanceJoint;
  82911. var MotorEnabledJoint = /** @class */ (function (_super) {
  82912. __extends(MotorEnabledJoint, _super);
  82913. function MotorEnabledJoint(type, jointData) {
  82914. return _super.call(this, type, jointData) || this;
  82915. }
  82916. /**
  82917. * Set the motor values.
  82918. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82919. * @param {number} force the force to apply
  82920. * @param {number} maxForce max force for this motor.
  82921. */
  82922. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82923. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82924. };
  82925. /**
  82926. * Set the motor's limits.
  82927. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82928. */
  82929. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82930. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82931. };
  82932. return MotorEnabledJoint;
  82933. }(PhysicsJoint));
  82934. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82935. /**
  82936. * This class represents a single hinge physics joint
  82937. */
  82938. var HingeJoint = /** @class */ (function (_super) {
  82939. __extends(HingeJoint, _super);
  82940. function HingeJoint(jointData) {
  82941. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82942. }
  82943. /**
  82944. * Set the motor values.
  82945. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82946. * @param {number} force the force to apply
  82947. * @param {number} maxForce max force for this motor.
  82948. */
  82949. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82950. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82951. };
  82952. /**
  82953. * Set the motor's limits.
  82954. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82955. */
  82956. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82957. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82958. };
  82959. return HingeJoint;
  82960. }(MotorEnabledJoint));
  82961. BABYLON.HingeJoint = HingeJoint;
  82962. /**
  82963. * This class represents a dual hinge physics joint (same as wheel joint)
  82964. */
  82965. var Hinge2Joint = /** @class */ (function (_super) {
  82966. __extends(Hinge2Joint, _super);
  82967. function Hinge2Joint(jointData) {
  82968. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82969. }
  82970. /**
  82971. * Set the motor values.
  82972. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82973. * @param {number} force the force to apply
  82974. * @param {number} maxForce max force for this motor.
  82975. * @param {motorIndex} the motor's index, 0 or 1.
  82976. */
  82977. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82978. if (motorIndex === void 0) { motorIndex = 0; }
  82979. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82980. };
  82981. /**
  82982. * Set the motor limits.
  82983. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82984. * @param {number} upperLimit the upper limit
  82985. * @param {number} lowerLimit lower limit
  82986. * @param {motorIndex} the motor's index, 0 or 1.
  82987. */
  82988. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82989. if (motorIndex === void 0) { motorIndex = 0; }
  82990. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82991. };
  82992. return Hinge2Joint;
  82993. }(MotorEnabledJoint));
  82994. BABYLON.Hinge2Joint = Hinge2Joint;
  82995. })(BABYLON || (BABYLON = {}));
  82996. //# sourceMappingURL=babylon.physicsJoint.js.map
  82997. var BABYLON;
  82998. (function (BABYLON) {
  82999. var PhysicsImpostor = /** @class */ (function () {
  83000. function PhysicsImpostor(object, type, _options, _scene) {
  83001. if (_options === void 0) { _options = { mass: 0 }; }
  83002. var _this = this;
  83003. this.object = object;
  83004. this.type = type;
  83005. this._options = _options;
  83006. this._scene = _scene;
  83007. this._bodyUpdateRequired = false;
  83008. this._onBeforePhysicsStepCallbacks = new Array();
  83009. this._onAfterPhysicsStepCallbacks = new Array();
  83010. this._onPhysicsCollideCallbacks = [];
  83011. this._deltaPosition = BABYLON.Vector3.Zero();
  83012. this._isDisposed = false;
  83013. //temp variables for parent rotation calculations
  83014. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83015. this._tmpQuat = new BABYLON.Quaternion();
  83016. this._tmpQuat2 = new BABYLON.Quaternion();
  83017. /**
  83018. * this function is executed by the physics engine.
  83019. */
  83020. this.beforeStep = function () {
  83021. if (!_this._physicsEngine) {
  83022. return;
  83023. }
  83024. _this.object.translate(_this._deltaPosition, -1);
  83025. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83026. _this.object.computeWorldMatrix(false);
  83027. if (_this.object.parent && _this.object.rotationQuaternion) {
  83028. _this.getParentsRotation();
  83029. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83030. }
  83031. else {
  83032. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83033. }
  83034. if (!_this._options.disableBidirectionalTransformation) {
  83035. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83036. }
  83037. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83038. func(_this);
  83039. });
  83040. };
  83041. /**
  83042. * this function is executed by the physics engine.
  83043. */
  83044. this.afterStep = function () {
  83045. if (!_this._physicsEngine) {
  83046. return;
  83047. }
  83048. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83049. func(_this);
  83050. });
  83051. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83052. // object has now its world rotation. needs to be converted to local.
  83053. if (_this.object.parent && _this.object.rotationQuaternion) {
  83054. _this.getParentsRotation();
  83055. _this._tmpQuat.conjugateInPlace();
  83056. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83057. }
  83058. // take the position set and make it the absolute position of this object.
  83059. _this.object.setAbsolutePosition(_this.object.position);
  83060. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83061. _this.object.translate(_this._deltaPosition, 1);
  83062. };
  83063. /**
  83064. * Legacy collision detection event support
  83065. */
  83066. this.onCollideEvent = null;
  83067. //event and body object due to cannon's event-based architecture.
  83068. this.onCollide = function (e) {
  83069. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83070. return;
  83071. }
  83072. if (!_this._physicsEngine) {
  83073. return;
  83074. }
  83075. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83076. if (otherImpostor) {
  83077. // Legacy collision detection event support
  83078. if (_this.onCollideEvent) {
  83079. _this.onCollideEvent(_this, otherImpostor);
  83080. }
  83081. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83082. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83083. }).forEach(function (obj) {
  83084. obj.callback(_this, otherImpostor);
  83085. });
  83086. }
  83087. };
  83088. //sanity check!
  83089. if (!this.object) {
  83090. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83091. return;
  83092. }
  83093. //legacy support for old syntax.
  83094. if (!this._scene && object.getScene) {
  83095. this._scene = object.getScene();
  83096. }
  83097. if (!this._scene) {
  83098. return;
  83099. }
  83100. this._physicsEngine = this._scene.getPhysicsEngine();
  83101. if (!this._physicsEngine) {
  83102. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83103. }
  83104. else {
  83105. //set the object's quaternion, if not set
  83106. if (!this.object.rotationQuaternion) {
  83107. if (this.object.rotation) {
  83108. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83109. }
  83110. else {
  83111. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83112. }
  83113. }
  83114. //default options params
  83115. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83116. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83117. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83118. this._joints = [];
  83119. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83120. if (!this.object.parent || this._options.ignoreParent) {
  83121. this._init();
  83122. }
  83123. else if (this.object.parent.physicsImpostor) {
  83124. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83125. }
  83126. }
  83127. }
  83128. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83129. get: function () {
  83130. return this._isDisposed;
  83131. },
  83132. enumerable: true,
  83133. configurable: true
  83134. });
  83135. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83136. get: function () {
  83137. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83138. },
  83139. set: function (value) {
  83140. this.setMass(value);
  83141. },
  83142. enumerable: true,
  83143. configurable: true
  83144. });
  83145. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83146. get: function () {
  83147. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83148. },
  83149. set: function (value) {
  83150. if (!this._physicsEngine) {
  83151. return;
  83152. }
  83153. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83154. },
  83155. enumerable: true,
  83156. configurable: true
  83157. });
  83158. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83159. get: function () {
  83160. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83161. },
  83162. set: function (value) {
  83163. if (!this._physicsEngine) {
  83164. return;
  83165. }
  83166. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83167. },
  83168. enumerable: true,
  83169. configurable: true
  83170. });
  83171. /**
  83172. * This function will completly initialize this impostor.
  83173. * It will create a new body - but only if this mesh has no parent.
  83174. * If it has, this impostor will not be used other than to define the impostor
  83175. * of the child mesh.
  83176. */
  83177. PhysicsImpostor.prototype._init = function () {
  83178. if (!this._physicsEngine) {
  83179. return;
  83180. }
  83181. this._physicsEngine.removeImpostor(this);
  83182. this.physicsBody = null;
  83183. this._parent = this._parent || this._getPhysicsParent();
  83184. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83185. this._physicsEngine.addImpostor(this);
  83186. }
  83187. };
  83188. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83189. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83190. var parentMesh = this.object.parent;
  83191. return parentMesh.physicsImpostor;
  83192. }
  83193. return null;
  83194. };
  83195. /**
  83196. * Should a new body be generated.
  83197. */
  83198. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83199. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83200. };
  83201. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83202. this.forceUpdate();
  83203. };
  83204. /**
  83205. * Force a regeneration of this or the parent's impostor's body.
  83206. * Use under cautious - This will remove all joints already implemented.
  83207. */
  83208. PhysicsImpostor.prototype.forceUpdate = function () {
  83209. this._init();
  83210. if (this.parent && !this._options.ignoreParent) {
  83211. this.parent.forceUpdate();
  83212. }
  83213. };
  83214. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83215. /*public get mesh(): AbstractMesh {
  83216. return this._mesh;
  83217. }*/
  83218. /**
  83219. * Gets the body that holds this impostor. Either its own, or its parent.
  83220. */
  83221. get: function () {
  83222. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83223. },
  83224. /**
  83225. * Set the physics body. Used mainly by the physics engine/plugin
  83226. */
  83227. set: function (physicsBody) {
  83228. if (this._physicsBody && this._physicsEngine) {
  83229. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83230. }
  83231. this._physicsBody = physicsBody;
  83232. this.resetUpdateFlags();
  83233. },
  83234. enumerable: true,
  83235. configurable: true
  83236. });
  83237. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83238. get: function () {
  83239. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83240. },
  83241. set: function (value) {
  83242. this._parent = value;
  83243. },
  83244. enumerable: true,
  83245. configurable: true
  83246. });
  83247. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83248. this._bodyUpdateRequired = false;
  83249. };
  83250. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83251. if (this.object.getBoundingInfo) {
  83252. var q = this.object.rotationQuaternion;
  83253. //reset rotation
  83254. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83255. //calculate the world matrix with no rotation
  83256. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83257. var boundingInfo = this.object.getBoundingInfo();
  83258. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83259. //bring back the rotation
  83260. this.object.rotationQuaternion = q;
  83261. //calculate the world matrix with the new rotation
  83262. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83263. return size;
  83264. }
  83265. else {
  83266. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83267. }
  83268. };
  83269. PhysicsImpostor.prototype.getObjectCenter = function () {
  83270. if (this.object.getBoundingInfo) {
  83271. var boundingInfo = this.object.getBoundingInfo();
  83272. return boundingInfo.boundingBox.centerWorld;
  83273. }
  83274. else {
  83275. return this.object.position;
  83276. }
  83277. };
  83278. /**
  83279. * Get a specific parametes from the options parameter.
  83280. */
  83281. PhysicsImpostor.prototype.getParam = function (paramName) {
  83282. return this._options[paramName];
  83283. };
  83284. /**
  83285. * Sets a specific parameter in the options given to the physics plugin
  83286. */
  83287. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83288. this._options[paramName] = value;
  83289. this._bodyUpdateRequired = true;
  83290. };
  83291. /**
  83292. * Specifically change the body's mass option. Won't recreate the physics body object
  83293. */
  83294. PhysicsImpostor.prototype.setMass = function (mass) {
  83295. if (this.getParam("mass") !== mass) {
  83296. this.setParam("mass", mass);
  83297. }
  83298. if (this._physicsEngine) {
  83299. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83300. }
  83301. };
  83302. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83304. };
  83305. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83306. if (this._physicsEngine) {
  83307. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83308. }
  83309. };
  83310. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83311. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83312. };
  83313. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83314. if (this._physicsEngine) {
  83315. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83316. }
  83317. };
  83318. /**
  83319. * Execute a function with the physics plugin native code.
  83320. * Provide a function the will have two variables - the world object and the physics body object.
  83321. */
  83322. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83323. if (this._physicsEngine) {
  83324. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83325. }
  83326. };
  83327. /**
  83328. * Register a function that will be executed before the physics world is stepping forward.
  83329. */
  83330. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83331. this._onBeforePhysicsStepCallbacks.push(func);
  83332. };
  83333. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83334. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83335. if (index > -1) {
  83336. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83337. }
  83338. else {
  83339. BABYLON.Tools.Warn("Function to remove was not found");
  83340. }
  83341. };
  83342. /**
  83343. * Register a function that will be executed after the physics step
  83344. */
  83345. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83346. this._onAfterPhysicsStepCallbacks.push(func);
  83347. };
  83348. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83349. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83350. if (index > -1) {
  83351. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83352. }
  83353. else {
  83354. BABYLON.Tools.Warn("Function to remove was not found");
  83355. }
  83356. };
  83357. /**
  83358. * register a function that will be executed when this impostor collides against a different body.
  83359. */
  83360. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83361. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83362. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83363. };
  83364. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83365. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83366. var index = -1;
  83367. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83368. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83369. // chcek the arrays match
  83370. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83371. return collidedAgainstList.indexOf(impostor) > -1;
  83372. });
  83373. if (sameList) {
  83374. index = idx;
  83375. }
  83376. return sameList;
  83377. }
  83378. return false;
  83379. });
  83380. if (found) {
  83381. this._onPhysicsCollideCallbacks.splice(index, 1);
  83382. }
  83383. else {
  83384. BABYLON.Tools.Warn("Function to remove was not found");
  83385. }
  83386. };
  83387. PhysicsImpostor.prototype.getParentsRotation = function () {
  83388. var parent = this.object.parent;
  83389. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83390. while (parent) {
  83391. if (parent.rotationQuaternion) {
  83392. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83393. }
  83394. else {
  83395. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83396. }
  83397. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83398. parent = parent.parent;
  83399. }
  83400. return this._tmpQuat;
  83401. };
  83402. /**
  83403. * Apply a force
  83404. */
  83405. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83406. if (this._physicsEngine) {
  83407. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83408. }
  83409. return this;
  83410. };
  83411. /**
  83412. * Apply an impulse
  83413. */
  83414. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83415. if (this._physicsEngine) {
  83416. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83417. }
  83418. return this;
  83419. };
  83420. /**
  83421. * A help function to create a joint.
  83422. */
  83423. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83424. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83425. this.addJoint(otherImpostor, joint);
  83426. return this;
  83427. };
  83428. /**
  83429. * Add a joint to this impostor with a different impostor.
  83430. */
  83431. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83432. this._joints.push({
  83433. otherImpostor: otherImpostor,
  83434. joint: joint
  83435. });
  83436. if (this._physicsEngine) {
  83437. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83438. }
  83439. return this;
  83440. };
  83441. /**
  83442. * Will keep this body still, in a sleep mode.
  83443. */
  83444. PhysicsImpostor.prototype.sleep = function () {
  83445. if (this._physicsEngine) {
  83446. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83447. }
  83448. return this;
  83449. };
  83450. /**
  83451. * Wake the body up.
  83452. */
  83453. PhysicsImpostor.prototype.wakeUp = function () {
  83454. if (this._physicsEngine) {
  83455. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83456. }
  83457. return this;
  83458. };
  83459. PhysicsImpostor.prototype.clone = function (newObject) {
  83460. if (!newObject)
  83461. return null;
  83462. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83463. };
  83464. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83465. var _this = this;
  83466. //no dispose if no physics engine is available.
  83467. if (!this._physicsEngine) {
  83468. return;
  83469. }
  83470. this._joints.forEach(function (j) {
  83471. if (_this._physicsEngine) {
  83472. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83473. }
  83474. });
  83475. //dispose the physics body
  83476. this._physicsEngine.removeImpostor(this);
  83477. if (this.parent) {
  83478. this.parent.forceUpdate();
  83479. }
  83480. else {
  83481. /*this._object.getChildMeshes().forEach(function(mesh) {
  83482. if (mesh.physicsImpostor) {
  83483. if (disposeChildren) {
  83484. mesh.physicsImpostor.dispose();
  83485. mesh.physicsImpostor = null;
  83486. }
  83487. }
  83488. })*/
  83489. }
  83490. this._isDisposed = true;
  83491. };
  83492. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83493. this._deltaPosition.copyFrom(position);
  83494. };
  83495. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83496. if (!this._deltaRotation) {
  83497. this._deltaRotation = new BABYLON.Quaternion();
  83498. }
  83499. this._deltaRotation.copyFrom(rotation);
  83500. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83501. };
  83502. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83503. if (this._physicsEngine) {
  83504. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83505. }
  83506. return this;
  83507. };
  83508. PhysicsImpostor.prototype.getRadius = function () {
  83509. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83510. };
  83511. /**
  83512. * Sync a bone with this impostor
  83513. * @param bone The bone to sync to the impostor.
  83514. * @param boneMesh The mesh that the bone is influencing.
  83515. * @param jointPivot The pivot of the joint / bone in local space.
  83516. * @param distToJoint Optional distance from the impostor to the joint.
  83517. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83518. */
  83519. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83520. var tempVec = PhysicsImpostor._tmpVecs[0];
  83521. var mesh = this.object;
  83522. if (mesh.rotationQuaternion) {
  83523. if (adjustRotation) {
  83524. var tempQuat = PhysicsImpostor._tmpQuat;
  83525. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83526. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83527. }
  83528. else {
  83529. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83530. }
  83531. }
  83532. tempVec.x = 0;
  83533. tempVec.y = 0;
  83534. tempVec.z = 0;
  83535. if (jointPivot) {
  83536. tempVec.x = jointPivot.x;
  83537. tempVec.y = jointPivot.y;
  83538. tempVec.z = jointPivot.z;
  83539. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83540. if (distToJoint === undefined || distToJoint === null) {
  83541. distToJoint = jointPivot.length();
  83542. }
  83543. tempVec.x *= distToJoint;
  83544. tempVec.y *= distToJoint;
  83545. tempVec.z *= distToJoint;
  83546. }
  83547. if (bone.getParent()) {
  83548. tempVec.addInPlace(mesh.getAbsolutePosition());
  83549. bone.setAbsolutePosition(tempVec, boneMesh);
  83550. }
  83551. else {
  83552. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83553. boneMesh.position.x -= tempVec.x;
  83554. boneMesh.position.y -= tempVec.y;
  83555. boneMesh.position.z -= tempVec.z;
  83556. }
  83557. };
  83558. /**
  83559. * Sync impostor to a bone
  83560. * @param bone The bone that the impostor will be synced to.
  83561. * @param boneMesh The mesh that the bone is influencing.
  83562. * @param jointPivot The pivot of the joint / bone in local space.
  83563. * @param distToJoint Optional distance from the impostor to the joint.
  83564. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83565. * @param boneAxis Optional vector3 axis the bone is aligned with
  83566. */
  83567. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83568. var mesh = this.object;
  83569. if (mesh.rotationQuaternion) {
  83570. if (adjustRotation) {
  83571. var tempQuat = PhysicsImpostor._tmpQuat;
  83572. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83573. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83574. }
  83575. else {
  83576. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83577. }
  83578. }
  83579. var pos = PhysicsImpostor._tmpVecs[0];
  83580. var boneDir = PhysicsImpostor._tmpVecs[1];
  83581. if (!boneAxis) {
  83582. boneAxis = PhysicsImpostor._tmpVecs[2];
  83583. boneAxis.x = 0;
  83584. boneAxis.y = 1;
  83585. boneAxis.z = 0;
  83586. }
  83587. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83588. bone.getAbsolutePositionToRef(boneMesh, pos);
  83589. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83590. distToJoint = jointPivot.length();
  83591. }
  83592. if (distToJoint !== undefined && distToJoint !== null) {
  83593. pos.x += boneDir.x * distToJoint;
  83594. pos.y += boneDir.y * distToJoint;
  83595. pos.z += boneDir.z * distToJoint;
  83596. }
  83597. mesh.setAbsolutePosition(pos);
  83598. };
  83599. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83600. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83601. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83602. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83603. //Impostor types
  83604. PhysicsImpostor.NoImpostor = 0;
  83605. PhysicsImpostor.SphereImpostor = 1;
  83606. PhysicsImpostor.BoxImpostor = 2;
  83607. PhysicsImpostor.PlaneImpostor = 3;
  83608. PhysicsImpostor.MeshImpostor = 4;
  83609. PhysicsImpostor.CylinderImpostor = 7;
  83610. PhysicsImpostor.ParticleImpostor = 8;
  83611. PhysicsImpostor.HeightmapImpostor = 9;
  83612. return PhysicsImpostor;
  83613. }());
  83614. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83615. })(BABYLON || (BABYLON = {}));
  83616. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83617. var BABYLON;
  83618. (function (BABYLON) {
  83619. var PhysicsEngine = /** @class */ (function () {
  83620. function PhysicsEngine(gravity, _physicsPlugin) {
  83621. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83622. this._physicsPlugin = _physicsPlugin;
  83623. //new methods and parameters
  83624. this._impostors = [];
  83625. this._joints = [];
  83626. if (!this._physicsPlugin.isSupported()) {
  83627. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83628. + "Please make sure it is included.");
  83629. }
  83630. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83631. this.setGravity(gravity);
  83632. this.setTimeStep();
  83633. }
  83634. PhysicsEngine.prototype.setGravity = function (gravity) {
  83635. this.gravity = gravity;
  83636. this._physicsPlugin.setGravity(this.gravity);
  83637. };
  83638. /**
  83639. * Set the time step of the physics engine.
  83640. * default is 1/60.
  83641. * To slow it down, enter 1/600 for example.
  83642. * To speed it up, 1/30
  83643. * @param {number} newTimeStep the new timestep to apply to this world.
  83644. */
  83645. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83646. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83647. this._physicsPlugin.setTimeStep(newTimeStep);
  83648. };
  83649. /**
  83650. * Get the time step of the physics engine.
  83651. */
  83652. PhysicsEngine.prototype.getTimeStep = function () {
  83653. return this._physicsPlugin.getTimeStep();
  83654. };
  83655. PhysicsEngine.prototype.dispose = function () {
  83656. this._impostors.forEach(function (impostor) {
  83657. impostor.dispose();
  83658. });
  83659. this._physicsPlugin.dispose();
  83660. };
  83661. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83662. return this._physicsPlugin.name;
  83663. };
  83664. /**
  83665. * Adding a new impostor for the impostor tracking.
  83666. * This will be done by the impostor itself.
  83667. * @param {PhysicsImpostor} impostor the impostor to add
  83668. */
  83669. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83670. impostor.uniqueId = this._impostors.push(impostor);
  83671. //if no parent, generate the body
  83672. if (!impostor.parent) {
  83673. this._physicsPlugin.generatePhysicsBody(impostor);
  83674. }
  83675. };
  83676. /**
  83677. * Remove an impostor from the engine.
  83678. * This impostor and its mesh will not longer be updated by the physics engine.
  83679. * @param {PhysicsImpostor} impostor the impostor to remove
  83680. */
  83681. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83682. var index = this._impostors.indexOf(impostor);
  83683. if (index > -1) {
  83684. var removed = this._impostors.splice(index, 1);
  83685. //Is it needed?
  83686. if (removed.length) {
  83687. //this will also remove it from the world.
  83688. removed[0].physicsBody = null;
  83689. }
  83690. }
  83691. };
  83692. /**
  83693. * Add a joint to the physics engine
  83694. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83695. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83696. * @param {PhysicsJoint} the joint that will connect both impostors.
  83697. */
  83698. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83699. var impostorJoint = {
  83700. mainImpostor: mainImpostor,
  83701. connectedImpostor: connectedImpostor,
  83702. joint: joint
  83703. };
  83704. joint.physicsPlugin = this._physicsPlugin;
  83705. this._joints.push(impostorJoint);
  83706. this._physicsPlugin.generateJoint(impostorJoint);
  83707. };
  83708. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83709. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83710. return (impostorJoint.connectedImpostor === connectedImpostor
  83711. && impostorJoint.joint === joint
  83712. && impostorJoint.mainImpostor === mainImpostor);
  83713. });
  83714. if (matchingJoints.length) {
  83715. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83716. //TODO remove it from the list as well
  83717. }
  83718. };
  83719. /**
  83720. * Called by the scene. no need to call it.
  83721. */
  83722. PhysicsEngine.prototype._step = function (delta) {
  83723. var _this = this;
  83724. //check if any mesh has no body / requires an update
  83725. this._impostors.forEach(function (impostor) {
  83726. if (impostor.isBodyInitRequired()) {
  83727. _this._physicsPlugin.generatePhysicsBody(impostor);
  83728. }
  83729. });
  83730. if (delta > 0.1) {
  83731. delta = 0.1;
  83732. }
  83733. else if (delta <= 0) {
  83734. delta = 1.0 / 60.0;
  83735. }
  83736. this._physicsPlugin.executeStep(delta, this._impostors);
  83737. };
  83738. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83739. return this._physicsPlugin;
  83740. };
  83741. PhysicsEngine.prototype.getImpostors = function () {
  83742. return this._impostors;
  83743. };
  83744. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83745. for (var i = 0; i < this._impostors.length; ++i) {
  83746. if (this._impostors[i].object === object) {
  83747. return this._impostors[i];
  83748. }
  83749. }
  83750. return null;
  83751. };
  83752. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83753. for (var i = 0; i < this._impostors.length; ++i) {
  83754. if (this._impostors[i].physicsBody === body) {
  83755. return this._impostors[i];
  83756. }
  83757. }
  83758. return null;
  83759. };
  83760. // Statics
  83761. PhysicsEngine.Epsilon = 0.001;
  83762. return PhysicsEngine;
  83763. }());
  83764. BABYLON.PhysicsEngine = PhysicsEngine;
  83765. })(BABYLON || (BABYLON = {}));
  83766. //# sourceMappingURL=babylon.physicsEngine.js.map
  83767. var BABYLON;
  83768. (function (BABYLON) {
  83769. var PhysicsHelper = /** @class */ (function () {
  83770. function PhysicsHelper(scene) {
  83771. this._scene = scene;
  83772. this._physicsEngine = this._scene.getPhysicsEngine();
  83773. if (!this._physicsEngine) {
  83774. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83775. }
  83776. }
  83777. /**
  83778. * @param {Vector3} origin the origin of the explosion
  83779. * @param {number} radius the explosion radius
  83780. * @param {number} strength the explosion strength
  83781. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83782. */
  83783. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83784. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83785. if (!this._physicsEngine) {
  83786. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83787. return null;
  83788. }
  83789. var impostors = this._physicsEngine.getImpostors();
  83790. if (impostors.length === 0) {
  83791. return null;
  83792. }
  83793. var event = new PhysicsRadialExplosionEvent(this._scene);
  83794. impostors.forEach(function (impostor) {
  83795. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83796. if (!impostorForceAndContactPoint) {
  83797. return;
  83798. }
  83799. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83800. });
  83801. event.dispose(false);
  83802. return event;
  83803. };
  83804. /**
  83805. * @param {Vector3} origin the origin of the explosion
  83806. * @param {number} radius the explosion radius
  83807. * @param {number} strength the explosion strength
  83808. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83809. */
  83810. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83811. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83812. if (!this._physicsEngine) {
  83813. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83814. return null;
  83815. }
  83816. var impostors = this._physicsEngine.getImpostors();
  83817. if (impostors.length === 0) {
  83818. return null;
  83819. }
  83820. var event = new PhysicsRadialExplosionEvent(this._scene);
  83821. impostors.forEach(function (impostor) {
  83822. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83823. if (!impostorForceAndContactPoint) {
  83824. return;
  83825. }
  83826. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83827. });
  83828. event.dispose(false);
  83829. return event;
  83830. };
  83831. /**
  83832. * @param {Vector3} origin the origin of the explosion
  83833. * @param {number} radius the explosion radius
  83834. * @param {number} strength the explosion strength
  83835. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83836. */
  83837. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83838. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83839. if (!this._physicsEngine) {
  83840. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83841. return null;
  83842. }
  83843. var impostors = this._physicsEngine.getImpostors();
  83844. if (impostors.length === 0) {
  83845. return null;
  83846. }
  83847. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83848. event.dispose(false);
  83849. return event;
  83850. };
  83851. /**
  83852. * @param {Vector3} origin the origin of the updraft
  83853. * @param {number} radius the radius of the updraft
  83854. * @param {number} strength the strength of the updraft
  83855. * @param {number} height the height of the updraft
  83856. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83857. */
  83858. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83859. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83860. if (!this._physicsEngine) {
  83861. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83862. return null;
  83863. }
  83864. if (this._physicsEngine.getImpostors().length === 0) {
  83865. return null;
  83866. }
  83867. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83868. event.dispose(false);
  83869. return event;
  83870. };
  83871. /**
  83872. * @param {Vector3} origin the of the vortex
  83873. * @param {number} radius the radius of the vortex
  83874. * @param {number} strength the strength of the vortex
  83875. * @param {number} height the height of the vortex
  83876. */
  83877. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83878. if (!this._physicsEngine) {
  83879. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83880. return null;
  83881. }
  83882. if (this._physicsEngine.getImpostors().length === 0) {
  83883. return null;
  83884. }
  83885. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83886. event.dispose(false);
  83887. return event;
  83888. };
  83889. return PhysicsHelper;
  83890. }());
  83891. BABYLON.PhysicsHelper = PhysicsHelper;
  83892. /***** Radial explosion *****/
  83893. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83894. function PhysicsRadialExplosionEvent(scene) {
  83895. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83896. this._rays = [];
  83897. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83898. this._scene = scene;
  83899. }
  83900. /**
  83901. * Returns the data related to the radial explosion event (sphere & rays).
  83902. * @returns {PhysicsRadialExplosionEventData}
  83903. */
  83904. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83905. this._dataFetched = true;
  83906. return {
  83907. sphere: this._sphere,
  83908. rays: this._rays,
  83909. };
  83910. };
  83911. /**
  83912. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83913. * @param impostor
  83914. * @param {Vector3} origin the origin of the explosion
  83915. * @param {number} radius the explosion radius
  83916. * @param {number} strength the explosion strength
  83917. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83918. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83919. */
  83920. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83921. if (impostor.mass === 0) {
  83922. return null;
  83923. }
  83924. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83925. return null;
  83926. }
  83927. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83928. return null;
  83929. }
  83930. var impostorObjectCenter = impostor.getObjectCenter();
  83931. var direction = impostorObjectCenter.subtract(origin);
  83932. var ray = new BABYLON.Ray(origin, direction, radius);
  83933. this._rays.push(ray);
  83934. var hit = ray.intersectsMesh(impostor.object);
  83935. var contactPoint = hit.pickedPoint;
  83936. if (!contactPoint) {
  83937. return null;
  83938. }
  83939. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83940. if (distanceFromOrigin > radius) {
  83941. return null;
  83942. }
  83943. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83944. ? strength
  83945. : strength * (1 - (distanceFromOrigin / radius));
  83946. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83947. return { force: force, contactPoint: contactPoint };
  83948. };
  83949. /**
  83950. * Disposes the sphere.
  83951. * @param {bolean} force
  83952. */
  83953. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83954. var _this = this;
  83955. if (force === void 0) { force = true; }
  83956. if (force) {
  83957. this._sphere.dispose();
  83958. }
  83959. else {
  83960. setTimeout(function () {
  83961. if (!_this._dataFetched) {
  83962. _this._sphere.dispose();
  83963. }
  83964. }, 0);
  83965. }
  83966. };
  83967. /*** Helpers ***/
  83968. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83969. if (!this._sphere) {
  83970. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83971. this._sphere.isVisible = false;
  83972. }
  83973. };
  83974. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83975. var impostorObject = impostor.object;
  83976. this._prepareSphere();
  83977. this._sphere.position = origin;
  83978. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83979. this._sphere._updateBoundingInfo();
  83980. this._sphere.computeWorldMatrix(true);
  83981. return this._sphere.intersectsMesh(impostorObject, true);
  83982. };
  83983. return PhysicsRadialExplosionEvent;
  83984. }());
  83985. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83986. /***** Gravitational Field *****/
  83987. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83988. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83989. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83990. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83991. this._physicsHelper = physicsHelper;
  83992. this._scene = scene;
  83993. this._origin = origin;
  83994. this._radius = radius;
  83995. this._strength = strength;
  83996. this._falloff = falloff;
  83997. this._tickCallback = this._tick.bind(this);
  83998. }
  83999. /**
  84000. * Returns the data related to the gravitational field event (sphere).
  84001. * @returns {PhysicsGravitationalFieldEventData}
  84002. */
  84003. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84004. this._dataFetched = true;
  84005. return {
  84006. sphere: this._sphere,
  84007. };
  84008. };
  84009. /**
  84010. * Enables the gravitational field.
  84011. */
  84012. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84013. this._tickCallback.call(this);
  84014. this._scene.registerBeforeRender(this._tickCallback);
  84015. };
  84016. /**
  84017. * Disables the gravitational field.
  84018. */
  84019. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84020. this._scene.unregisterBeforeRender(this._tickCallback);
  84021. };
  84022. /**
  84023. * Disposes the sphere.
  84024. * @param {bolean} force
  84025. */
  84026. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84027. var _this = this;
  84028. if (force === void 0) { force = true; }
  84029. if (force) {
  84030. this._sphere.dispose();
  84031. }
  84032. else {
  84033. setTimeout(function () {
  84034. if (!_this._dataFetched) {
  84035. _this._sphere.dispose();
  84036. }
  84037. }, 0);
  84038. }
  84039. };
  84040. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84041. // Since the params won't change, we fetch the event only once
  84042. if (this._sphere) {
  84043. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84044. }
  84045. else {
  84046. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84047. if (radialExplosionEvent) {
  84048. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84049. }
  84050. }
  84051. };
  84052. return PhysicsGravitationalFieldEvent;
  84053. }());
  84054. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84055. /***** Updraft *****/
  84056. var PhysicsUpdraftEvent = /** @class */ (function () {
  84057. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84058. this._scene = _scene;
  84059. this._origin = _origin;
  84060. this._radius = _radius;
  84061. this._strength = _strength;
  84062. this._height = _height;
  84063. this._updraftMode = _updraftMode;
  84064. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84065. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84066. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84067. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84068. this._physicsEngine = this._scene.getPhysicsEngine();
  84069. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84070. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84071. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84072. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84073. }
  84074. this._tickCallback = this._tick.bind(this);
  84075. }
  84076. /**
  84077. * Returns the data related to the updraft event (cylinder).
  84078. * @returns {PhysicsUpdraftEventData}
  84079. */
  84080. PhysicsUpdraftEvent.prototype.getData = function () {
  84081. this._dataFetched = true;
  84082. return {
  84083. cylinder: this._cylinder,
  84084. };
  84085. };
  84086. /**
  84087. * Enables the updraft.
  84088. */
  84089. PhysicsUpdraftEvent.prototype.enable = function () {
  84090. this._tickCallback.call(this);
  84091. this._scene.registerBeforeRender(this._tickCallback);
  84092. };
  84093. /**
  84094. * Disables the cortex.
  84095. */
  84096. PhysicsUpdraftEvent.prototype.disable = function () {
  84097. this._scene.unregisterBeforeRender(this._tickCallback);
  84098. };
  84099. /**
  84100. * Disposes the sphere.
  84101. * @param {bolean} force
  84102. */
  84103. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84104. var _this = this;
  84105. if (force === void 0) { force = true; }
  84106. if (force) {
  84107. this._cylinder.dispose();
  84108. }
  84109. else {
  84110. setTimeout(function () {
  84111. if (!_this._dataFetched) {
  84112. _this._cylinder.dispose();
  84113. }
  84114. }, 0);
  84115. }
  84116. };
  84117. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84118. if (impostor.mass === 0) {
  84119. return null;
  84120. }
  84121. if (!this._intersectsWithCylinder(impostor)) {
  84122. return null;
  84123. }
  84124. var impostorObjectCenter = impostor.getObjectCenter();
  84125. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84126. var direction = this._originDirection;
  84127. }
  84128. else {
  84129. var direction = impostorObjectCenter.subtract(this._originTop);
  84130. }
  84131. var multiplier = this._strength * -1;
  84132. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84133. return { force: force, contactPoint: impostorObjectCenter };
  84134. };
  84135. PhysicsUpdraftEvent.prototype._tick = function () {
  84136. var _this = this;
  84137. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84138. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84139. if (!impostorForceAndContactPoint) {
  84140. return;
  84141. }
  84142. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84143. });
  84144. };
  84145. /*** Helpers ***/
  84146. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84147. if (!this._cylinder) {
  84148. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84149. height: this._height,
  84150. diameter: this._radius * 2,
  84151. }, this._scene);
  84152. this._cylinder.isVisible = false;
  84153. }
  84154. };
  84155. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84156. var impostorObject = impostor.object;
  84157. this._prepareCylinder();
  84158. this._cylinder.position = this._cylinderPosition;
  84159. return this._cylinder.intersectsMesh(impostorObject, true);
  84160. };
  84161. return PhysicsUpdraftEvent;
  84162. }());
  84163. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84164. /***** Vortex *****/
  84165. var PhysicsVortexEvent = /** @class */ (function () {
  84166. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84167. this._scene = _scene;
  84168. this._origin = _origin;
  84169. this._radius = _radius;
  84170. this._strength = _strength;
  84171. this._height = _height;
  84172. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84173. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84174. this._updraftMultiplier = 0.02;
  84175. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84176. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84177. this._physicsEngine = this._scene.getPhysicsEngine();
  84178. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84179. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84180. this._tickCallback = this._tick.bind(this);
  84181. }
  84182. /**
  84183. * Returns the data related to the vortex event (cylinder).
  84184. * @returns {PhysicsVortexEventData}
  84185. */
  84186. PhysicsVortexEvent.prototype.getData = function () {
  84187. this._dataFetched = true;
  84188. return {
  84189. cylinder: this._cylinder,
  84190. };
  84191. };
  84192. /**
  84193. * Enables the vortex.
  84194. */
  84195. PhysicsVortexEvent.prototype.enable = function () {
  84196. this._tickCallback.call(this);
  84197. this._scene.registerBeforeRender(this._tickCallback);
  84198. };
  84199. /**
  84200. * Disables the cortex.
  84201. */
  84202. PhysicsVortexEvent.prototype.disable = function () {
  84203. this._scene.unregisterBeforeRender(this._tickCallback);
  84204. };
  84205. /**
  84206. * Disposes the sphere.
  84207. * @param {bolean} force
  84208. */
  84209. PhysicsVortexEvent.prototype.dispose = function (force) {
  84210. var _this = this;
  84211. if (force === void 0) { force = true; }
  84212. if (force) {
  84213. this._cylinder.dispose();
  84214. }
  84215. else {
  84216. setTimeout(function () {
  84217. if (!_this._dataFetched) {
  84218. _this._cylinder.dispose();
  84219. }
  84220. }, 0);
  84221. }
  84222. };
  84223. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84224. if (impostor.mass === 0) {
  84225. return null;
  84226. }
  84227. if (!this._intersectsWithCylinder(impostor)) {
  84228. return null;
  84229. }
  84230. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84231. return null;
  84232. }
  84233. var impostorObjectCenter = impostor.getObjectCenter();
  84234. 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)
  84235. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84236. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84237. var hit = ray.intersectsMesh(impostor.object);
  84238. var contactPoint = hit.pickedPoint;
  84239. if (!contactPoint) {
  84240. return null;
  84241. }
  84242. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84243. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84244. var directionToOrigin = contactPoint.normalize();
  84245. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84246. directionToOrigin = directionToOrigin.negate();
  84247. }
  84248. // TODO: find a more physically based solution
  84249. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84250. var forceX = directionToOrigin.x * this._strength / 8;
  84251. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84252. var forceZ = directionToOrigin.z * this._strength / 8;
  84253. }
  84254. else {
  84255. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84256. var forceY = this._originTop.y * this._updraftMultiplier;
  84257. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84258. }
  84259. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84260. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84261. return { force: force, contactPoint: impostorObjectCenter };
  84262. };
  84263. PhysicsVortexEvent.prototype._tick = function () {
  84264. var _this = this;
  84265. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84266. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84267. if (!impostorForceAndContactPoint) {
  84268. return;
  84269. }
  84270. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84271. });
  84272. };
  84273. /*** Helpers ***/
  84274. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84275. if (!this._cylinder) {
  84276. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84277. height: this._height,
  84278. diameter: this._radius * 2,
  84279. }, this._scene);
  84280. this._cylinder.isVisible = false;
  84281. }
  84282. };
  84283. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84284. var impostorObject = impostor.object;
  84285. this._prepareCylinder();
  84286. this._cylinder.position = this._cylinderPosition;
  84287. return this._cylinder.intersectsMesh(impostorObject, true);
  84288. };
  84289. return PhysicsVortexEvent;
  84290. }());
  84291. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84292. /***** Enums *****/
  84293. /**
  84294. * The strenght of the force in correspondence to the distance of the affected object
  84295. */
  84296. var PhysicsRadialImpulseFalloff;
  84297. (function (PhysicsRadialImpulseFalloff) {
  84298. /** Defines that impulse is constant in strength across it's whole radius */
  84299. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84300. /** DEfines that impulse gets weaker if it's further from the origin */
  84301. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84302. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84303. /**
  84304. * The strenght of the force in correspondence to the distance of the affected object
  84305. */
  84306. var PhysicsUpdraftMode;
  84307. (function (PhysicsUpdraftMode) {
  84308. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84309. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84310. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84311. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84312. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84313. })(BABYLON || (BABYLON = {}));
  84314. //# sourceMappingURL=babylon.physicsHelper.js.map
  84315. var BABYLON;
  84316. (function (BABYLON) {
  84317. var CannonJSPlugin = /** @class */ (function () {
  84318. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84319. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84320. if (iterations === void 0) { iterations = 10; }
  84321. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84322. this.name = "CannonJSPlugin";
  84323. this._physicsMaterials = new Array();
  84324. this._fixedTimeStep = 1 / 60;
  84325. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84326. this.BJSCANNON = CANNON;
  84327. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84328. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84329. this._tmpPosition = BABYLON.Vector3.Zero();
  84330. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84331. this._tmpUnityRotation = new BABYLON.Quaternion();
  84332. if (!this.isSupported()) {
  84333. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84334. return;
  84335. }
  84336. this._extendNamespace();
  84337. this.world = new this.BJSCANNON.World();
  84338. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84339. this.world.solver.iterations = iterations;
  84340. }
  84341. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84342. this.world.gravity.copy(gravity);
  84343. };
  84344. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84345. this._fixedTimeStep = timeStep;
  84346. };
  84347. CannonJSPlugin.prototype.getTimeStep = function () {
  84348. return this._fixedTimeStep;
  84349. };
  84350. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84351. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84352. };
  84353. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84354. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84355. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84356. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84357. };
  84358. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84359. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84360. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84361. impostor.physicsBody.applyForce(impulse, worldPoint);
  84362. };
  84363. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84364. //parent-child relationship. Does this impostor has a parent impostor?
  84365. if (impostor.parent) {
  84366. if (impostor.physicsBody) {
  84367. this.removePhysicsBody(impostor);
  84368. //TODO is that needed?
  84369. impostor.forceUpdate();
  84370. }
  84371. return;
  84372. }
  84373. //should a new body be created for this impostor?
  84374. if (impostor.isBodyInitRequired()) {
  84375. var shape = this._createShape(impostor);
  84376. //unregister events, if body is being changed
  84377. var oldBody = impostor.physicsBody;
  84378. if (oldBody) {
  84379. this.removePhysicsBody(impostor);
  84380. }
  84381. //create the body and material
  84382. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84383. var bodyCreationObject = {
  84384. mass: impostor.getParam("mass"),
  84385. material: material
  84386. };
  84387. // A simple extend, in case native options were used.
  84388. var nativeOptions = impostor.getParam("nativeOptions");
  84389. for (var key in nativeOptions) {
  84390. if (nativeOptions.hasOwnProperty(key)) {
  84391. bodyCreationObject[key] = nativeOptions[key];
  84392. }
  84393. }
  84394. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84395. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84396. this.world.addEventListener("preStep", impostor.beforeStep);
  84397. this.world.addEventListener("postStep", impostor.afterStep);
  84398. impostor.physicsBody.addShape(shape);
  84399. this.world.add(impostor.physicsBody);
  84400. //try to keep the body moving in the right direction by taking old properties.
  84401. //Should be tested!
  84402. if (oldBody) {
  84403. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84404. impostor.physicsBody[param].copy(oldBody[param]);
  84405. });
  84406. }
  84407. this._processChildMeshes(impostor);
  84408. }
  84409. //now update the body's transformation
  84410. this._updatePhysicsBodyTransformation(impostor);
  84411. };
  84412. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84413. var _this = this;
  84414. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84415. var currentRotation = mainImpostor.object.rotationQuaternion;
  84416. if (meshChildren.length) {
  84417. var processMesh = function (localPosition, mesh) {
  84418. if (!currentRotation || !mesh.rotationQuaternion) {
  84419. return;
  84420. }
  84421. var childImpostor = mesh.getPhysicsImpostor();
  84422. if (childImpostor) {
  84423. var parent = childImpostor.parent;
  84424. if (parent !== mainImpostor) {
  84425. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84426. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84427. if (childImpostor.physicsBody) {
  84428. _this.removePhysicsBody(childImpostor);
  84429. childImpostor.physicsBody = null;
  84430. }
  84431. childImpostor.parent = mainImpostor;
  84432. childImpostor.resetUpdateFlags();
  84433. 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));
  84434. //Add the mass of the children.
  84435. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84436. }
  84437. }
  84438. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84439. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84440. };
  84441. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84442. }
  84443. };
  84444. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84445. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84446. this.world.removeEventListener("preStep", impostor.beforeStep);
  84447. this.world.removeEventListener("postStep", impostor.afterStep);
  84448. this.world.remove(impostor.physicsBody);
  84449. };
  84450. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84451. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84452. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84453. if (!mainBody || !connectedBody) {
  84454. return;
  84455. }
  84456. var constraint;
  84457. var jointData = impostorJoint.joint.jointData;
  84458. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84459. var constraintData = {
  84460. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84461. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84462. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84463. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84464. maxForce: jointData.nativeParams.maxForce,
  84465. collideConnected: !!jointData.collision
  84466. };
  84467. switch (impostorJoint.joint.type) {
  84468. case BABYLON.PhysicsJoint.HingeJoint:
  84469. case BABYLON.PhysicsJoint.Hinge2Joint:
  84470. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84471. break;
  84472. case BABYLON.PhysicsJoint.DistanceJoint:
  84473. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84474. break;
  84475. case BABYLON.PhysicsJoint.SpringJoint:
  84476. var springData = jointData;
  84477. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84478. restLength: springData.length,
  84479. stiffness: springData.stiffness,
  84480. damping: springData.damping,
  84481. localAnchorA: constraintData.pivotA,
  84482. localAnchorB: constraintData.pivotB
  84483. });
  84484. break;
  84485. case BABYLON.PhysicsJoint.LockJoint:
  84486. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84487. break;
  84488. case BABYLON.PhysicsJoint.PointToPointJoint:
  84489. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84490. default:
  84491. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84492. break;
  84493. }
  84494. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84495. constraint.collideConnected = !!jointData.collision;
  84496. impostorJoint.joint.physicsJoint = constraint;
  84497. //don't add spring as constraint, as it is not one.
  84498. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84499. this.world.addConstraint(constraint);
  84500. }
  84501. else {
  84502. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84503. constraint.applyForce();
  84504. });
  84505. }
  84506. };
  84507. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84508. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84509. };
  84510. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84511. var index;
  84512. var mat;
  84513. for (index = 0; index < this._physicsMaterials.length; index++) {
  84514. mat = this._physicsMaterials[index];
  84515. if (mat.friction === friction && mat.restitution === restitution) {
  84516. return mat;
  84517. }
  84518. }
  84519. var currentMat = new this.BJSCANNON.Material(name);
  84520. currentMat.friction = friction;
  84521. currentMat.restitution = restitution;
  84522. this._physicsMaterials.push(currentMat);
  84523. return currentMat;
  84524. };
  84525. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84526. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84527. };
  84528. CannonJSPlugin.prototype._createShape = function (impostor) {
  84529. var object = impostor.object;
  84530. var returnValue;
  84531. var extendSize = impostor.getObjectExtendSize();
  84532. switch (impostor.type) {
  84533. case BABYLON.PhysicsImpostor.SphereImpostor:
  84534. var radiusX = extendSize.x;
  84535. var radiusY = extendSize.y;
  84536. var radiusZ = extendSize.z;
  84537. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84538. break;
  84539. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84540. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84541. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84542. break;
  84543. case BABYLON.PhysicsImpostor.BoxImpostor:
  84544. var box = extendSize.scale(0.5);
  84545. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84546. break;
  84547. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84548. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84549. returnValue = new this.BJSCANNON.Plane();
  84550. break;
  84551. case BABYLON.PhysicsImpostor.MeshImpostor:
  84552. // should transform the vertex data to world coordinates!!
  84553. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84554. var rawFaces = object.getIndices ? object.getIndices() : [];
  84555. if (!rawVerts)
  84556. return;
  84557. // get only scale! so the object could transform correctly.
  84558. var oldPosition = object.position.clone();
  84559. var oldRotation = object.rotation && object.rotation.clone();
  84560. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84561. object.position.copyFromFloats(0, 0, 0);
  84562. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84563. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84564. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84565. var transform = object.computeWorldMatrix(true);
  84566. // convert rawVerts to object space
  84567. var temp = new Array();
  84568. var index;
  84569. for (index = 0; index < rawVerts.length; index += 3) {
  84570. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84571. }
  84572. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84573. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84574. //now set back the transformation!
  84575. object.position.copyFrom(oldPosition);
  84576. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84577. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84578. break;
  84579. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84580. var oldPosition2 = object.position.clone();
  84581. var oldRotation2 = object.rotation && object.rotation.clone();
  84582. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84583. object.position.copyFromFloats(0, 0, 0);
  84584. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84585. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84586. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84587. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84588. returnValue = this._createHeightmap(object);
  84589. object.position.copyFrom(oldPosition2);
  84590. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84591. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84592. object.computeWorldMatrix(true);
  84593. break;
  84594. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84595. returnValue = new this.BJSCANNON.Particle();
  84596. break;
  84597. }
  84598. return returnValue;
  84599. };
  84600. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84601. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84602. var transform = object.computeWorldMatrix(true);
  84603. // convert rawVerts to object space
  84604. var temp = new Array();
  84605. var index;
  84606. for (index = 0; index < pos.length; index += 3) {
  84607. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84608. }
  84609. pos = temp;
  84610. var matrix = new Array();
  84611. //For now pointDepth will not be used and will be automatically calculated.
  84612. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84613. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84614. var boundingInfo = object.getBoundingInfo();
  84615. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84616. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84617. var elementSize = dim * 2 / arraySize;
  84618. for (var i = 0; i < pos.length; i = i + 3) {
  84619. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84620. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84621. var y = -pos[i + 2] + minY;
  84622. if (!matrix[x]) {
  84623. matrix[x] = [];
  84624. }
  84625. if (!matrix[x][z]) {
  84626. matrix[x][z] = y;
  84627. }
  84628. matrix[x][z] = Math.max(y, matrix[x][z]);
  84629. }
  84630. for (var x = 0; x <= arraySize; ++x) {
  84631. if (!matrix[x]) {
  84632. var loc = 1;
  84633. while (!matrix[(x + loc) % arraySize]) {
  84634. loc++;
  84635. }
  84636. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84637. //console.log("missing x", x);
  84638. }
  84639. for (var z = 0; z <= arraySize; ++z) {
  84640. if (!matrix[x][z]) {
  84641. var loc = 1;
  84642. var newValue;
  84643. while (newValue === undefined) {
  84644. newValue = matrix[x][(z + loc++) % arraySize];
  84645. }
  84646. matrix[x][z] = newValue;
  84647. }
  84648. }
  84649. }
  84650. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84651. elementSize: elementSize
  84652. });
  84653. //For future reference, needed for body transformation
  84654. shape.minY = minY;
  84655. return shape;
  84656. };
  84657. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84658. var object = impostor.object;
  84659. //make sure it is updated...
  84660. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84661. // The delta between the mesh position and the mesh bounding box center
  84662. var bInfo = object.getBoundingInfo();
  84663. if (!bInfo)
  84664. return;
  84665. var center = impostor.getObjectCenter();
  84666. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84667. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84668. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84669. this._tmpPosition.copyFrom(center);
  84670. var quaternion = object.rotationQuaternion;
  84671. if (!quaternion) {
  84672. return;
  84673. }
  84674. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84675. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84676. //-90 DEG in X, precalculated
  84677. quaternion = quaternion.multiply(this._minus90X);
  84678. //Invert! (Precalculated, 90 deg in X)
  84679. //No need to clone. this will never change.
  84680. impostor.setDeltaRotation(this._plus90X);
  84681. }
  84682. //If it is a heightfield, if should be centered.
  84683. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84684. var mesh = object;
  84685. var boundingInfo = mesh.getBoundingInfo();
  84686. //calculate the correct body position:
  84687. var rotationQuaternion = mesh.rotationQuaternion;
  84688. mesh.rotationQuaternion = this._tmpUnityRotation;
  84689. mesh.computeWorldMatrix(true);
  84690. //get original center with no rotation
  84691. var c = center.clone();
  84692. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84693. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84694. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84695. mesh.setPreTransformMatrix(p);
  84696. mesh.computeWorldMatrix(true);
  84697. //calculate the translation
  84698. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84699. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84700. //add it inverted to the delta
  84701. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84702. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84703. //rotation is back
  84704. mesh.rotationQuaternion = rotationQuaternion;
  84705. mesh.setPreTransformMatrix(oldPivot);
  84706. mesh.computeWorldMatrix(true);
  84707. }
  84708. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84709. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84710. //this._tmpPosition.copyFrom(object.position);
  84711. }
  84712. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84713. //Now update the impostor object
  84714. impostor.physicsBody.position.copy(this._tmpPosition);
  84715. impostor.physicsBody.quaternion.copy(quaternion);
  84716. };
  84717. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84718. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84719. if (impostor.object.rotationQuaternion) {
  84720. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84721. }
  84722. };
  84723. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84724. impostor.physicsBody.position.copy(newPosition);
  84725. impostor.physicsBody.quaternion.copy(newRotation);
  84726. };
  84727. CannonJSPlugin.prototype.isSupported = function () {
  84728. return this.BJSCANNON !== undefined;
  84729. };
  84730. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84731. impostor.physicsBody.velocity.copy(velocity);
  84732. };
  84733. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84734. impostor.physicsBody.angularVelocity.copy(velocity);
  84735. };
  84736. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84737. var v = impostor.physicsBody.velocity;
  84738. if (!v) {
  84739. return null;
  84740. }
  84741. return new BABYLON.Vector3(v.x, v.y, v.z);
  84742. };
  84743. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84744. var v = impostor.physicsBody.angularVelocity;
  84745. if (!v) {
  84746. return null;
  84747. }
  84748. return new BABYLON.Vector3(v.x, v.y, v.z);
  84749. };
  84750. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84751. impostor.physicsBody.mass = mass;
  84752. impostor.physicsBody.updateMassProperties();
  84753. };
  84754. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84755. return impostor.physicsBody.mass;
  84756. };
  84757. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84758. return impostor.physicsBody.material.friction;
  84759. };
  84760. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84761. impostor.physicsBody.material.friction = friction;
  84762. };
  84763. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84764. return impostor.physicsBody.material.restitution;
  84765. };
  84766. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84767. impostor.physicsBody.material.restitution = restitution;
  84768. };
  84769. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84770. impostor.physicsBody.sleep();
  84771. };
  84772. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84773. impostor.physicsBody.wakeUp();
  84774. };
  84775. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84776. joint.physicsJoint.distance = maxDistance;
  84777. };
  84778. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84779. // if (!motorIndex) {
  84780. // joint.physicsJoint.enableMotor();
  84781. // }
  84782. // }
  84783. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84784. // if (!motorIndex) {
  84785. // joint.physicsJoint.disableMotor();
  84786. // }
  84787. // }
  84788. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84789. if (!motorIndex) {
  84790. joint.physicsJoint.enableMotor();
  84791. joint.physicsJoint.setMotorSpeed(speed);
  84792. if (maxForce) {
  84793. this.setLimit(joint, maxForce);
  84794. }
  84795. }
  84796. };
  84797. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84798. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84799. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84800. };
  84801. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84802. var body = impostor.physicsBody;
  84803. mesh.position.x = body.position.x;
  84804. mesh.position.y = body.position.y;
  84805. mesh.position.z = body.position.z;
  84806. if (mesh.rotationQuaternion) {
  84807. mesh.rotationQuaternion.x = body.quaternion.x;
  84808. mesh.rotationQuaternion.y = body.quaternion.y;
  84809. mesh.rotationQuaternion.z = body.quaternion.z;
  84810. mesh.rotationQuaternion.w = body.quaternion.w;
  84811. }
  84812. };
  84813. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84814. var shape = impostor.physicsBody.shapes[0];
  84815. return shape.boundingSphereRadius;
  84816. };
  84817. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84818. var shape = impostor.physicsBody.shapes[0];
  84819. result.x = shape.halfExtents.x * 2;
  84820. result.y = shape.halfExtents.y * 2;
  84821. result.z = shape.halfExtents.z * 2;
  84822. };
  84823. CannonJSPlugin.prototype.dispose = function () {
  84824. };
  84825. CannonJSPlugin.prototype._extendNamespace = function () {
  84826. //this will force cannon to execute at least one step when using interpolation
  84827. var step_tmp1 = new this.BJSCANNON.Vec3();
  84828. var Engine = this.BJSCANNON;
  84829. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84830. maxSubSteps = maxSubSteps || 10;
  84831. timeSinceLastCalled = timeSinceLastCalled || 0;
  84832. if (timeSinceLastCalled === 0) {
  84833. this.internalStep(dt);
  84834. this.time += dt;
  84835. }
  84836. else {
  84837. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84838. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84839. var t0 = performance.now();
  84840. for (var i = 0; i !== internalSteps; i++) {
  84841. this.internalStep(dt);
  84842. if (performance.now() - t0 > dt * 1000) {
  84843. break;
  84844. }
  84845. }
  84846. this.time += timeSinceLastCalled;
  84847. var h = this.time % dt;
  84848. var h_div_dt = h / dt;
  84849. var interpvelo = step_tmp1;
  84850. var bodies = this.bodies;
  84851. for (var j = 0; j !== bodies.length; j++) {
  84852. var b = bodies[j];
  84853. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84854. b.position.vsub(b.previousPosition, interpvelo);
  84855. interpvelo.scale(h_div_dt, interpvelo);
  84856. b.position.vadd(interpvelo, b.interpolatedPosition);
  84857. }
  84858. else {
  84859. b.interpolatedPosition.copy(b.position);
  84860. b.interpolatedQuaternion.copy(b.quaternion);
  84861. }
  84862. }
  84863. }
  84864. };
  84865. };
  84866. return CannonJSPlugin;
  84867. }());
  84868. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84869. })(BABYLON || (BABYLON = {}));
  84870. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84871. var BABYLON;
  84872. (function (BABYLON) {
  84873. var OimoJSPlugin = /** @class */ (function () {
  84874. function OimoJSPlugin(iterations) {
  84875. this.name = "OimoJSPlugin";
  84876. this._tmpImpostorsArray = [];
  84877. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84878. this.BJSOIMO = OIMO;
  84879. this.world = new this.BJSOIMO.World({
  84880. iterations: iterations
  84881. });
  84882. this.world.clear();
  84883. }
  84884. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84885. this.world.gravity.copy(gravity);
  84886. };
  84887. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84888. this.world.timeStep = timeStep;
  84889. };
  84890. OimoJSPlugin.prototype.getTimeStep = function () {
  84891. return this.world.timeStep;
  84892. };
  84893. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84894. var _this = this;
  84895. impostors.forEach(function (impostor) {
  84896. impostor.beforeStep();
  84897. });
  84898. this.world.step();
  84899. impostors.forEach(function (impostor) {
  84900. impostor.afterStep();
  84901. //update the ordered impostors array
  84902. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84903. });
  84904. //check for collisions
  84905. var contact = this.world.contacts;
  84906. while (contact !== null) {
  84907. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84908. contact = contact.next;
  84909. continue;
  84910. }
  84911. //is this body colliding with any other? get the impostor
  84912. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84913. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84914. if (!mainImpostor || !collidingImpostor) {
  84915. contact = contact.next;
  84916. continue;
  84917. }
  84918. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84919. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84920. contact = contact.next;
  84921. }
  84922. };
  84923. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84924. var mass = impostor.physicsBody.mass;
  84925. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84926. };
  84927. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84928. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84929. this.applyImpulse(impostor, force, contactPoint);
  84930. };
  84931. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84932. var _this = this;
  84933. //parent-child relationship. Does this impostor has a parent impostor?
  84934. if (impostor.parent) {
  84935. if (impostor.physicsBody) {
  84936. this.removePhysicsBody(impostor);
  84937. //TODO is that needed?
  84938. impostor.forceUpdate();
  84939. }
  84940. return;
  84941. }
  84942. if (impostor.isBodyInitRequired()) {
  84943. var bodyConfig = {
  84944. name: impostor.uniqueId,
  84945. //Oimo must have mass, also for static objects.
  84946. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84947. size: [],
  84948. type: [],
  84949. pos: [],
  84950. posShape: [],
  84951. rot: [],
  84952. rotShape: [],
  84953. move: impostor.getParam("mass") !== 0,
  84954. density: impostor.getParam("mass"),
  84955. friction: impostor.getParam("friction"),
  84956. restitution: impostor.getParam("restitution"),
  84957. //Supporting older versions of Oimo
  84958. world: this.world
  84959. };
  84960. var impostors = [impostor];
  84961. var addToArray = function (parent) {
  84962. if (!parent.getChildMeshes)
  84963. return;
  84964. parent.getChildMeshes().forEach(function (m) {
  84965. if (m.physicsImpostor) {
  84966. impostors.push(m.physicsImpostor);
  84967. //m.physicsImpostor._init();
  84968. }
  84969. });
  84970. };
  84971. addToArray(impostor.object);
  84972. var checkWithEpsilon_1 = function (value) {
  84973. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84974. };
  84975. impostors.forEach(function (i) {
  84976. if (!i.object.rotationQuaternion) {
  84977. return;
  84978. }
  84979. //get the correct bounding box
  84980. var oldQuaternion = i.object.rotationQuaternion;
  84981. var rot = oldQuaternion.toEulerAngles();
  84982. var extendSize = i.getObjectExtendSize();
  84983. var radToDeg = 57.295779513082320876;
  84984. if (i === impostor) {
  84985. var center = impostor.getObjectCenter();
  84986. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84987. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84988. //Can also use Array.prototype.push.apply
  84989. bodyConfig.pos.push(center.x);
  84990. bodyConfig.pos.push(center.y);
  84991. bodyConfig.pos.push(center.z);
  84992. bodyConfig.posShape.push(0, 0, 0);
  84993. //tmp solution
  84994. bodyConfig.rot.push(rot.x * radToDeg);
  84995. bodyConfig.rot.push(rot.y * radToDeg);
  84996. bodyConfig.rot.push(rot.z * radToDeg);
  84997. bodyConfig.rotShape.push(0, 0, 0);
  84998. }
  84999. else {
  85000. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85001. bodyConfig.posShape.push(localPosition.x);
  85002. bodyConfig.posShape.push(localPosition.y);
  85003. bodyConfig.posShape.push(localPosition.z);
  85004. bodyConfig.pos.push(0, 0, 0);
  85005. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85006. bodyConfig.rot.push(0);
  85007. bodyConfig.rot.push(0);
  85008. bodyConfig.rot.push(0);
  85009. bodyConfig.rotShape.push(rot.x * radToDeg);
  85010. bodyConfig.rotShape.push(rot.y * radToDeg);
  85011. bodyConfig.rotShape.push(rot.z * radToDeg);
  85012. }
  85013. // register mesh
  85014. switch (i.type) {
  85015. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85016. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85017. case BABYLON.PhysicsImpostor.SphereImpostor:
  85018. var radiusX = extendSize.x;
  85019. var radiusY = extendSize.y;
  85020. var radiusZ = extendSize.z;
  85021. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85022. bodyConfig.type.push('sphere');
  85023. //due to the way oimo works with compounds, add 3 times
  85024. bodyConfig.size.push(size);
  85025. bodyConfig.size.push(size);
  85026. bodyConfig.size.push(size);
  85027. break;
  85028. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85029. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85030. var sizeY = checkWithEpsilon_1(extendSize.y);
  85031. bodyConfig.type.push('cylinder');
  85032. bodyConfig.size.push(sizeX);
  85033. bodyConfig.size.push(sizeY);
  85034. //due to the way oimo works with compounds, add one more value.
  85035. bodyConfig.size.push(sizeY);
  85036. break;
  85037. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85038. case BABYLON.PhysicsImpostor.BoxImpostor:
  85039. default:
  85040. var sizeX = checkWithEpsilon_1(extendSize.x);
  85041. var sizeY = checkWithEpsilon_1(extendSize.y);
  85042. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85043. bodyConfig.type.push('box');
  85044. //if (i === impostor) {
  85045. bodyConfig.size.push(sizeX);
  85046. bodyConfig.size.push(sizeY);
  85047. bodyConfig.size.push(sizeZ);
  85048. //} else {
  85049. // bodyConfig.size.push(0,0,0);
  85050. //}
  85051. break;
  85052. }
  85053. //actually not needed, but hey...
  85054. i.object.rotationQuaternion = oldQuaternion;
  85055. });
  85056. impostor.physicsBody = this.world.add(bodyConfig);
  85057. }
  85058. else {
  85059. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85060. }
  85061. impostor.setDeltaPosition(this._tmpPositionVector);
  85062. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85063. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85064. };
  85065. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85066. //impostor.physicsBody.dispose();
  85067. //Same as : (older oimo versions)
  85068. this.world.removeRigidBody(impostor.physicsBody);
  85069. };
  85070. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85071. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85072. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85073. if (!mainBody || !connectedBody) {
  85074. return;
  85075. }
  85076. var jointData = impostorJoint.joint.jointData;
  85077. var options = jointData.nativeParams || {};
  85078. var type;
  85079. var nativeJointData = {
  85080. body1: mainBody,
  85081. body2: connectedBody,
  85082. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85083. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85084. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85085. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85086. min: options.min,
  85087. max: options.max,
  85088. collision: options.collision || jointData.collision,
  85089. spring: options.spring,
  85090. //supporting older version of Oimo
  85091. world: this.world
  85092. };
  85093. switch (impostorJoint.joint.type) {
  85094. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85095. type = "jointBall";
  85096. break;
  85097. case BABYLON.PhysicsJoint.SpringJoint:
  85098. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85099. var springData = jointData;
  85100. nativeJointData.min = springData.length || nativeJointData.min;
  85101. //Max should also be set, just make sure it is at least min
  85102. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85103. case BABYLON.PhysicsJoint.DistanceJoint:
  85104. type = "jointDistance";
  85105. nativeJointData.max = jointData.maxDistance;
  85106. break;
  85107. case BABYLON.PhysicsJoint.PrismaticJoint:
  85108. type = "jointPrisme";
  85109. break;
  85110. case BABYLON.PhysicsJoint.SliderJoint:
  85111. type = "jointSlide";
  85112. break;
  85113. case BABYLON.PhysicsJoint.WheelJoint:
  85114. type = "jointWheel";
  85115. break;
  85116. case BABYLON.PhysicsJoint.HingeJoint:
  85117. default:
  85118. type = "jointHinge";
  85119. break;
  85120. }
  85121. nativeJointData.type = type;
  85122. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85123. };
  85124. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85125. //Bug in Oimo prevents us from disposing a joint in the playground
  85126. //joint.joint.physicsJoint.dispose();
  85127. //So we will bruteforce it!
  85128. try {
  85129. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85130. }
  85131. catch (e) {
  85132. BABYLON.Tools.Warn(e);
  85133. }
  85134. };
  85135. OimoJSPlugin.prototype.isSupported = function () {
  85136. return this.BJSOIMO !== undefined;
  85137. };
  85138. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85139. if (!impostor.physicsBody.sleeping) {
  85140. //TODO check that
  85141. /*if (impostor.physicsBody.shapes.next) {
  85142. var parentShape = this._getLastShape(impostor.physicsBody);
  85143. impostor.object.position.copyFrom(parentShape.position);
  85144. console.log(parentShape.position);
  85145. } else {*/
  85146. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85147. //}
  85148. if (impostor.object.rotationQuaternion) {
  85149. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85150. }
  85151. }
  85152. };
  85153. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85154. var body = impostor.physicsBody;
  85155. body.position.copy(newPosition);
  85156. body.orientation.copy(newRotation);
  85157. body.syncShapes();
  85158. body.awake();
  85159. };
  85160. /*private _getLastShape(body: any): any {
  85161. var lastShape = body.shapes;
  85162. while (lastShape.next) {
  85163. lastShape = lastShape.next;
  85164. }
  85165. return lastShape;
  85166. }*/
  85167. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85168. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  85169. };
  85170. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85171. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  85172. };
  85173. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85174. var v = impostor.physicsBody.linearVelocity;
  85175. if (!v) {
  85176. return null;
  85177. }
  85178. return new BABYLON.Vector3(v.x, v.y, v.z);
  85179. };
  85180. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85181. var v = impostor.physicsBody.angularVelocity;
  85182. if (!v) {
  85183. return null;
  85184. }
  85185. return new BABYLON.Vector3(v.x, v.y, v.z);
  85186. };
  85187. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85188. var staticBody = mass === 0;
  85189. //this will actually set the body's density and not its mass.
  85190. //But this is how oimo treats the mass variable.
  85191. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85192. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85193. };
  85194. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85195. return impostor.physicsBody.shapes.density;
  85196. };
  85197. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85198. return impostor.physicsBody.shapes.friction;
  85199. };
  85200. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85201. impostor.physicsBody.shapes.friction = friction;
  85202. };
  85203. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85204. return impostor.physicsBody.shapes.restitution;
  85205. };
  85206. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85207. impostor.physicsBody.shapes.restitution = restitution;
  85208. };
  85209. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85210. impostor.physicsBody.sleep();
  85211. };
  85212. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85213. impostor.physicsBody.awake();
  85214. };
  85215. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85216. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85217. if (minDistance !== void 0) {
  85218. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85219. }
  85220. };
  85221. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85222. //TODO separate rotational and transational motors.
  85223. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85224. if (motor) {
  85225. motor.setMotor(speed, maxForce);
  85226. }
  85227. };
  85228. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85229. //TODO separate rotational and transational motors.
  85230. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85231. if (motor) {
  85232. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85233. }
  85234. };
  85235. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85236. var body = impostor.physicsBody;
  85237. mesh.position.x = body.position.x;
  85238. mesh.position.y = body.position.y;
  85239. mesh.position.z = body.position.z;
  85240. if (mesh.rotationQuaternion) {
  85241. mesh.rotationQuaternion.x = body.orientation.x;
  85242. mesh.rotationQuaternion.y = body.orientation.y;
  85243. mesh.rotationQuaternion.z = body.orientation.z;
  85244. mesh.rotationQuaternion.w = body.orientation.s;
  85245. }
  85246. };
  85247. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85248. return impostor.physicsBody.shapes.radius;
  85249. };
  85250. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85251. var shape = impostor.physicsBody.shapes;
  85252. result.x = shape.halfWidth * 2;
  85253. result.y = shape.halfHeight * 2;
  85254. result.z = shape.halfDepth * 2;
  85255. };
  85256. OimoJSPlugin.prototype.dispose = function () {
  85257. this.world.clear();
  85258. };
  85259. return OimoJSPlugin;
  85260. }());
  85261. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85262. })(BABYLON || (BABYLON = {}));
  85263. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85264. var BABYLON;
  85265. (function (BABYLON) {
  85266. /*
  85267. * Based on jsTGALoader - Javascript loader for TGA file
  85268. * By Vincent Thibault
  85269. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85270. */
  85271. var TGATools = /** @class */ (function () {
  85272. function TGATools() {
  85273. }
  85274. TGATools.GetTGAHeader = function (data) {
  85275. var offset = 0;
  85276. var header = {
  85277. id_length: data[offset++],
  85278. colormap_type: data[offset++],
  85279. image_type: data[offset++],
  85280. colormap_index: data[offset++] | data[offset++] << 8,
  85281. colormap_length: data[offset++] | data[offset++] << 8,
  85282. colormap_size: data[offset++],
  85283. origin: [
  85284. data[offset++] | data[offset++] << 8,
  85285. data[offset++] | data[offset++] << 8
  85286. ],
  85287. width: data[offset++] | data[offset++] << 8,
  85288. height: data[offset++] | data[offset++] << 8,
  85289. pixel_size: data[offset++],
  85290. flags: data[offset++]
  85291. };
  85292. return header;
  85293. };
  85294. TGATools.UploadContent = function (gl, data) {
  85295. // Not enough data to contain header ?
  85296. if (data.length < 19) {
  85297. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85298. return;
  85299. }
  85300. // Read Header
  85301. var offset = 18;
  85302. var header = TGATools.GetTGAHeader(data);
  85303. // Assume it's a valid Targa file.
  85304. if (header.id_length + offset > data.length) {
  85305. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85306. return;
  85307. }
  85308. // Skip not needed data
  85309. offset += header.id_length;
  85310. var use_rle = false;
  85311. var use_pal = false;
  85312. var use_grey = false;
  85313. // Get some informations.
  85314. switch (header.image_type) {
  85315. case TGATools._TYPE_RLE_INDEXED:
  85316. use_rle = true;
  85317. case TGATools._TYPE_INDEXED:
  85318. use_pal = true;
  85319. break;
  85320. case TGATools._TYPE_RLE_RGB:
  85321. use_rle = true;
  85322. case TGATools._TYPE_RGB:
  85323. // use_rgb = true;
  85324. break;
  85325. case TGATools._TYPE_RLE_GREY:
  85326. use_rle = true;
  85327. case TGATools._TYPE_GREY:
  85328. use_grey = true;
  85329. break;
  85330. }
  85331. var pixel_data;
  85332. // var numAlphaBits = header.flags & 0xf;
  85333. var pixel_size = header.pixel_size >> 3;
  85334. var pixel_total = header.width * header.height * pixel_size;
  85335. // Read palettes
  85336. var palettes;
  85337. if (use_pal) {
  85338. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85339. }
  85340. // Read LRE
  85341. if (use_rle) {
  85342. pixel_data = new Uint8Array(pixel_total);
  85343. var c, count, i;
  85344. var localOffset = 0;
  85345. var pixels = new Uint8Array(pixel_size);
  85346. while (offset < pixel_total && localOffset < pixel_total) {
  85347. c = data[offset++];
  85348. count = (c & 0x7f) + 1;
  85349. // RLE pixels
  85350. if (c & 0x80) {
  85351. // Bind pixel tmp array
  85352. for (i = 0; i < pixel_size; ++i) {
  85353. pixels[i] = data[offset++];
  85354. }
  85355. // Copy pixel array
  85356. for (i = 0; i < count; ++i) {
  85357. pixel_data.set(pixels, localOffset + i * pixel_size);
  85358. }
  85359. localOffset += pixel_size * count;
  85360. }
  85361. // Raw pixels
  85362. else {
  85363. count *= pixel_size;
  85364. for (i = 0; i < count; ++i) {
  85365. pixel_data[localOffset + i] = data[offset++];
  85366. }
  85367. localOffset += count;
  85368. }
  85369. }
  85370. }
  85371. // RAW Pixels
  85372. else {
  85373. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85374. }
  85375. // Load to texture
  85376. var x_start, y_start, x_step, y_step, y_end, x_end;
  85377. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85378. default:
  85379. case TGATools._ORIGIN_UL:
  85380. x_start = 0;
  85381. x_step = 1;
  85382. x_end = header.width;
  85383. y_start = 0;
  85384. y_step = 1;
  85385. y_end = header.height;
  85386. break;
  85387. case TGATools._ORIGIN_BL:
  85388. x_start = 0;
  85389. x_step = 1;
  85390. x_end = header.width;
  85391. y_start = header.height - 1;
  85392. y_step = -1;
  85393. y_end = -1;
  85394. break;
  85395. case TGATools._ORIGIN_UR:
  85396. x_start = header.width - 1;
  85397. x_step = -1;
  85398. x_end = -1;
  85399. y_start = 0;
  85400. y_step = 1;
  85401. y_end = header.height;
  85402. break;
  85403. case TGATools._ORIGIN_BR:
  85404. x_start = header.width - 1;
  85405. x_step = -1;
  85406. x_end = -1;
  85407. y_start = header.height - 1;
  85408. y_step = -1;
  85409. y_end = -1;
  85410. break;
  85411. }
  85412. // Load the specify method
  85413. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85414. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85415. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85416. };
  85417. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85418. var image = pixel_data, colormap = palettes;
  85419. var width = header.width, height = header.height;
  85420. var color, i = 0, x, y;
  85421. var imageData = new Uint8Array(width * height * 4);
  85422. for (y = y_start; y !== y_end; y += y_step) {
  85423. for (x = x_start; x !== x_end; x += x_step, i++) {
  85424. color = image[i];
  85425. imageData[(x + width * y) * 4 + 3] = 255;
  85426. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85427. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85428. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85429. }
  85430. }
  85431. return imageData;
  85432. };
  85433. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85434. var image = pixel_data;
  85435. var width = header.width, height = header.height;
  85436. var color, i = 0, x, y;
  85437. var imageData = new Uint8Array(width * height * 4);
  85438. for (y = y_start; y !== y_end; y += y_step) {
  85439. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85440. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85441. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85442. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85443. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85444. imageData[(x + width * y) * 4 + 0] = r;
  85445. imageData[(x + width * y) * 4 + 1] = g;
  85446. imageData[(x + width * y) * 4 + 2] = b;
  85447. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85448. }
  85449. }
  85450. return imageData;
  85451. };
  85452. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85453. var image = pixel_data;
  85454. var width = header.width, height = header.height;
  85455. var i = 0, x, y;
  85456. var imageData = new Uint8Array(width * height * 4);
  85457. for (y = y_start; y !== y_end; y += y_step) {
  85458. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85459. imageData[(x + width * y) * 4 + 3] = 255;
  85460. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85461. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85462. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85463. }
  85464. }
  85465. return imageData;
  85466. };
  85467. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85468. var image = pixel_data;
  85469. var width = header.width, height = header.height;
  85470. var i = 0, x, y;
  85471. var imageData = new Uint8Array(width * height * 4);
  85472. for (y = y_start; y !== y_end; y += y_step) {
  85473. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85474. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85475. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85476. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85477. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85478. }
  85479. }
  85480. return imageData;
  85481. };
  85482. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85483. var image = pixel_data;
  85484. var width = header.width, height = header.height;
  85485. var color, i = 0, x, y;
  85486. var imageData = new Uint8Array(width * height * 4);
  85487. for (y = y_start; y !== y_end; y += y_step) {
  85488. for (x = x_start; x !== x_end; x += x_step, i++) {
  85489. color = image[i];
  85490. imageData[(x + width * y) * 4 + 0] = color;
  85491. imageData[(x + width * y) * 4 + 1] = color;
  85492. imageData[(x + width * y) * 4 + 2] = color;
  85493. imageData[(x + width * y) * 4 + 3] = 255;
  85494. }
  85495. }
  85496. return imageData;
  85497. };
  85498. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85499. var image = pixel_data;
  85500. var width = header.width, height = header.height;
  85501. var i = 0, x, y;
  85502. var imageData = new Uint8Array(width * height * 4);
  85503. for (y = y_start; y !== y_end; y += y_step) {
  85504. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85505. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85506. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85507. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85508. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85509. }
  85510. }
  85511. return imageData;
  85512. };
  85513. //private static _TYPE_NO_DATA = 0;
  85514. TGATools._TYPE_INDEXED = 1;
  85515. TGATools._TYPE_RGB = 2;
  85516. TGATools._TYPE_GREY = 3;
  85517. TGATools._TYPE_RLE_INDEXED = 9;
  85518. TGATools._TYPE_RLE_RGB = 10;
  85519. TGATools._TYPE_RLE_GREY = 11;
  85520. TGATools._ORIGIN_MASK = 0x30;
  85521. TGATools._ORIGIN_SHIFT = 0x04;
  85522. TGATools._ORIGIN_BL = 0x00;
  85523. TGATools._ORIGIN_BR = 0x01;
  85524. TGATools._ORIGIN_UL = 0x02;
  85525. TGATools._ORIGIN_UR = 0x03;
  85526. return TGATools;
  85527. }());
  85528. BABYLON.TGATools = TGATools;
  85529. })(BABYLON || (BABYLON = {}));
  85530. //# sourceMappingURL=babylon.tga.js.map
  85531. var BABYLON;
  85532. (function (BABYLON) {
  85533. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85534. // All values and structures referenced from:
  85535. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85536. var DDS_MAGIC = 0x20534444;
  85537. var
  85538. //DDSD_CAPS = 0x1,
  85539. //DDSD_HEIGHT = 0x2,
  85540. //DDSD_WIDTH = 0x4,
  85541. //DDSD_PITCH = 0x8,
  85542. //DDSD_PIXELFORMAT = 0x1000,
  85543. DDSD_MIPMAPCOUNT = 0x20000;
  85544. //DDSD_LINEARSIZE = 0x80000,
  85545. //DDSD_DEPTH = 0x800000;
  85546. // var DDSCAPS_COMPLEX = 0x8,
  85547. // DDSCAPS_MIPMAP = 0x400000,
  85548. // DDSCAPS_TEXTURE = 0x1000;
  85549. var DDSCAPS2_CUBEMAP = 0x200;
  85550. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85551. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85552. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85553. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85554. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85555. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85556. // DDSCAPS2_VOLUME = 0x200000;
  85557. var
  85558. //DDPF_ALPHAPIXELS = 0x1,
  85559. //DDPF_ALPHA = 0x2,
  85560. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85561. //DDPF_YUV = 0x200,
  85562. DDPF_LUMINANCE = 0x20000;
  85563. function FourCCToInt32(value) {
  85564. return value.charCodeAt(0) +
  85565. (value.charCodeAt(1) << 8) +
  85566. (value.charCodeAt(2) << 16) +
  85567. (value.charCodeAt(3) << 24);
  85568. }
  85569. function Int32ToFourCC(value) {
  85570. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85571. }
  85572. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85573. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85574. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85575. var FOURCC_DX10 = FourCCToInt32("DX10");
  85576. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85577. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85578. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85579. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85580. var headerLengthInt = 31; // The header length in 32 bit ints
  85581. // Offsets into the header array
  85582. var off_magic = 0;
  85583. var off_size = 1;
  85584. var off_flags = 2;
  85585. var off_height = 3;
  85586. var off_width = 4;
  85587. var off_mipmapCount = 7;
  85588. var off_pfFlags = 20;
  85589. var off_pfFourCC = 21;
  85590. var off_RGBbpp = 22;
  85591. var off_RMask = 23;
  85592. var off_GMask = 24;
  85593. var off_BMask = 25;
  85594. var off_AMask = 26;
  85595. // var off_caps1 = 27;
  85596. var off_caps2 = 28;
  85597. // var off_caps3 = 29;
  85598. // var off_caps4 = 30;
  85599. var off_dxgiFormat = 32;
  85600. ;
  85601. var DDSTools = /** @class */ (function () {
  85602. function DDSTools() {
  85603. }
  85604. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85605. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85606. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85607. var mipmapCount = 1;
  85608. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85609. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85610. }
  85611. var fourCC = header[off_pfFourCC];
  85612. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85613. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85614. switch (fourCC) {
  85615. case FOURCC_D3DFMT_R16G16B16A16F:
  85616. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85617. break;
  85618. case FOURCC_D3DFMT_R32G32B32A32F:
  85619. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85620. break;
  85621. case FOURCC_DX10:
  85622. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85623. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85624. break;
  85625. }
  85626. }
  85627. return {
  85628. width: header[off_width],
  85629. height: header[off_height],
  85630. mipmapCount: mipmapCount,
  85631. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85632. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85633. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85634. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85635. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85636. dxgiFormat: dxgiFormat,
  85637. textureType: textureType
  85638. };
  85639. };
  85640. DDSTools._ToHalfFloat = function (value) {
  85641. if (!DDSTools._FloatView) {
  85642. DDSTools._FloatView = new Float32Array(1);
  85643. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85644. }
  85645. DDSTools._FloatView[0] = value;
  85646. var x = DDSTools._Int32View[0];
  85647. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85648. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85649. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85650. /* If zero, or denormal, or exponent underflows too much for a denormal
  85651. * half, return signed zero. */
  85652. if (e < 103) {
  85653. return bits;
  85654. }
  85655. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85656. if (e > 142) {
  85657. bits |= 0x7c00;
  85658. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85659. * not Inf, so make sure we set one mantissa bit too. */
  85660. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85661. return bits;
  85662. }
  85663. /* If exponent underflows but not too much, return a denormal */
  85664. if (e < 113) {
  85665. m |= 0x0800;
  85666. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85667. * to 1, which is OK. */
  85668. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85669. return bits;
  85670. }
  85671. bits |= ((e - 112) << 10) | (m >> 1);
  85672. bits += m & 1;
  85673. return bits;
  85674. };
  85675. DDSTools._FromHalfFloat = function (value) {
  85676. var s = (value & 0x8000) >> 15;
  85677. var e = (value & 0x7C00) >> 10;
  85678. var f = value & 0x03FF;
  85679. if (e === 0) {
  85680. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85681. }
  85682. else if (e == 0x1F) {
  85683. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85684. }
  85685. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85686. };
  85687. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85688. var destArray = new Float32Array(dataLength);
  85689. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85690. var index = 0;
  85691. for (var y = 0; y < height; y++) {
  85692. for (var x = 0; x < width; x++) {
  85693. var srcPos = (x + y * width) * 4;
  85694. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85695. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85696. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85697. if (DDSTools.StoreLODInAlphaChannel) {
  85698. destArray[index + 3] = lod;
  85699. }
  85700. else {
  85701. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85702. }
  85703. index += 4;
  85704. }
  85705. }
  85706. return destArray;
  85707. };
  85708. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85709. if (DDSTools.StoreLODInAlphaChannel) {
  85710. var destArray = new Uint16Array(dataLength);
  85711. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85712. var index = 0;
  85713. for (var y = 0; y < height; y++) {
  85714. for (var x = 0; x < width; x++) {
  85715. var srcPos = (x + y * width) * 4;
  85716. destArray[index] = srcData[srcPos];
  85717. destArray[index + 1] = srcData[srcPos + 1];
  85718. destArray[index + 2] = srcData[srcPos + 2];
  85719. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85720. index += 4;
  85721. }
  85722. }
  85723. return destArray;
  85724. }
  85725. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85726. };
  85727. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85728. if (DDSTools.StoreLODInAlphaChannel) {
  85729. var destArray = new Float32Array(dataLength);
  85730. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85731. var index = 0;
  85732. for (var y = 0; y < height; y++) {
  85733. for (var x = 0; x < width; x++) {
  85734. var srcPos = (x + y * width) * 4;
  85735. destArray[index] = srcData[srcPos];
  85736. destArray[index + 1] = srcData[srcPos + 1];
  85737. destArray[index + 2] = srcData[srcPos + 2];
  85738. destArray[index + 3] = lod;
  85739. index += 4;
  85740. }
  85741. }
  85742. return destArray;
  85743. }
  85744. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85745. };
  85746. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85747. var destArray = new Uint8Array(dataLength);
  85748. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85749. var index = 0;
  85750. for (var y = 0; y < height; y++) {
  85751. for (var x = 0; x < width; x++) {
  85752. var srcPos = (x + y * width) * 4;
  85753. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85754. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85755. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85756. if (DDSTools.StoreLODInAlphaChannel) {
  85757. destArray[index + 3] = lod;
  85758. }
  85759. else {
  85760. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85761. }
  85762. index += 4;
  85763. }
  85764. }
  85765. return destArray;
  85766. };
  85767. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85768. var destArray = new Uint8Array(dataLength);
  85769. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85770. var index = 0;
  85771. for (var y = 0; y < height; y++) {
  85772. for (var x = 0; x < width; x++) {
  85773. var srcPos = (x + y * width) * 4;
  85774. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85775. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85776. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85777. if (DDSTools.StoreLODInAlphaChannel) {
  85778. destArray[index + 3] = lod;
  85779. }
  85780. else {
  85781. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85782. }
  85783. index += 4;
  85784. }
  85785. }
  85786. return destArray;
  85787. };
  85788. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85789. var byteArray = new Uint8Array(dataLength);
  85790. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85791. var index = 0;
  85792. for (var y = 0; y < height; y++) {
  85793. for (var x = 0; x < width; x++) {
  85794. var srcPos = (x + y * width) * 4;
  85795. byteArray[index] = srcData[srcPos + rOffset];
  85796. byteArray[index + 1] = srcData[srcPos + gOffset];
  85797. byteArray[index + 2] = srcData[srcPos + bOffset];
  85798. byteArray[index + 3] = srcData[srcPos + aOffset];
  85799. index += 4;
  85800. }
  85801. }
  85802. return byteArray;
  85803. };
  85804. DDSTools._ExtractLongWordOrder = function (value) {
  85805. if (value === 0 || value === 255 || value === -16777216) {
  85806. return 0;
  85807. }
  85808. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85809. };
  85810. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85811. var byteArray = new Uint8Array(dataLength);
  85812. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85813. var index = 0;
  85814. for (var y = 0; y < height; y++) {
  85815. for (var x = 0; x < width; x++) {
  85816. var srcPos = (x + y * width) * 3;
  85817. byteArray[index] = srcData[srcPos + rOffset];
  85818. byteArray[index + 1] = srcData[srcPos + gOffset];
  85819. byteArray[index + 2] = srcData[srcPos + bOffset];
  85820. index += 3;
  85821. }
  85822. }
  85823. return byteArray;
  85824. };
  85825. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85826. var byteArray = new Uint8Array(dataLength);
  85827. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85828. var index = 0;
  85829. for (var y = 0; y < height; y++) {
  85830. for (var x = 0; x < width; x++) {
  85831. var srcPos = (x + y * width);
  85832. byteArray[index] = srcData[srcPos];
  85833. index++;
  85834. }
  85835. }
  85836. return byteArray;
  85837. };
  85838. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85839. if (lodIndex === void 0) { lodIndex = -1; }
  85840. var sphericalPolynomialFaces = null;
  85841. if (info.sphericalPolynomial) {
  85842. sphericalPolynomialFaces = new Array();
  85843. }
  85844. var ext = engine.getCaps().s3tc;
  85845. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85846. var fourCC, width, height, dataLength = 0, dataOffset;
  85847. var byteArray, mipmapCount, mip;
  85848. var internalFormat = 0;
  85849. var format = 0;
  85850. var blockBytes = 1;
  85851. if (header[off_magic] !== DDS_MAGIC) {
  85852. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85853. return;
  85854. }
  85855. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85856. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85857. return;
  85858. }
  85859. if (info.isCompressed && !ext) {
  85860. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85861. return;
  85862. }
  85863. var bpp = header[off_RGBbpp];
  85864. dataOffset = header[off_size] + 4;
  85865. var computeFormats = false;
  85866. if (info.isFourCC) {
  85867. fourCC = header[off_pfFourCC];
  85868. switch (fourCC) {
  85869. case FOURCC_DXT1:
  85870. blockBytes = 8;
  85871. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85872. break;
  85873. case FOURCC_DXT3:
  85874. blockBytes = 16;
  85875. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85876. break;
  85877. case FOURCC_DXT5:
  85878. blockBytes = 16;
  85879. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85880. break;
  85881. case FOURCC_D3DFMT_R16G16B16A16F:
  85882. computeFormats = true;
  85883. break;
  85884. case FOURCC_D3DFMT_R32G32B32A32F:
  85885. computeFormats = true;
  85886. break;
  85887. case FOURCC_DX10:
  85888. // There is an additionnal header so dataOffset need to be changed
  85889. dataOffset += 5 * 4; // 5 uints
  85890. var supported = false;
  85891. switch (info.dxgiFormat) {
  85892. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85893. computeFormats = true;
  85894. supported = true;
  85895. break;
  85896. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85897. info.isRGB = true;
  85898. info.isFourCC = false;
  85899. bpp = 32;
  85900. supported = true;
  85901. break;
  85902. }
  85903. if (supported) {
  85904. break;
  85905. }
  85906. default:
  85907. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85908. return;
  85909. }
  85910. }
  85911. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85912. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85913. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85914. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85915. if (computeFormats) {
  85916. format = engine._getWebGLTextureType(info.textureType);
  85917. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85918. }
  85919. mipmapCount = 1;
  85920. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85921. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85922. }
  85923. for (var face = 0; face < faces; face++) {
  85924. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85925. width = header[off_width];
  85926. height = header[off_height];
  85927. for (mip = 0; mip < mipmapCount; ++mip) {
  85928. if (lodIndex === -1 || lodIndex === mip) {
  85929. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85930. var i = (lodIndex === -1) ? mip : 0;
  85931. if (!info.isCompressed && info.isFourCC) {
  85932. dataLength = width * height * 4;
  85933. var floatArray = null;
  85934. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85935. if (bpp === 128) {
  85936. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85937. if (sphericalPolynomialFaces && i == 0) {
  85938. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85939. }
  85940. }
  85941. else if (bpp === 64) {
  85942. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85943. if (sphericalPolynomialFaces && i == 0) {
  85944. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85945. }
  85946. }
  85947. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85948. format = engine._getWebGLTextureType(info.textureType);
  85949. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85950. }
  85951. else {
  85952. if (bpp === 128) {
  85953. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85954. if (sphericalPolynomialFaces && i == 0) {
  85955. sphericalPolynomialFaces.push(floatArray);
  85956. }
  85957. }
  85958. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85959. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85960. if (sphericalPolynomialFaces && i == 0) {
  85961. sphericalPolynomialFaces.push(floatArray);
  85962. }
  85963. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85964. format = engine._getWebGLTextureType(info.textureType);
  85965. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85966. }
  85967. else { // 64
  85968. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85969. if (sphericalPolynomialFaces && i == 0) {
  85970. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85971. }
  85972. }
  85973. }
  85974. if (floatArray) {
  85975. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85976. }
  85977. }
  85978. else if (info.isRGB) {
  85979. if (bpp === 24) {
  85980. dataLength = width * height * 3;
  85981. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85982. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85983. }
  85984. else { // 32
  85985. dataLength = width * height * 4;
  85986. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85987. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85988. }
  85989. }
  85990. else if (info.isLuminance) {
  85991. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85992. var unpaddedRowSize = width;
  85993. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85994. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85995. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85996. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85997. }
  85998. else {
  85999. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86000. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86001. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86002. }
  86003. }
  86004. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86005. width *= 0.5;
  86006. height *= 0.5;
  86007. width = Math.max(1.0, width);
  86008. height = Math.max(1.0, height);
  86009. }
  86010. if (currentFace !== undefined) {
  86011. // Loading a single face
  86012. break;
  86013. }
  86014. }
  86015. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86016. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86017. size: header[off_width],
  86018. right: sphericalPolynomialFaces[0],
  86019. left: sphericalPolynomialFaces[1],
  86020. up: sphericalPolynomialFaces[2],
  86021. down: sphericalPolynomialFaces[3],
  86022. front: sphericalPolynomialFaces[4],
  86023. back: sphericalPolynomialFaces[5],
  86024. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86025. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86026. gammaSpace: false,
  86027. });
  86028. }
  86029. else {
  86030. info.sphericalPolynomial = undefined;
  86031. }
  86032. };
  86033. DDSTools.StoreLODInAlphaChannel = false;
  86034. return DDSTools;
  86035. }());
  86036. BABYLON.DDSTools = DDSTools;
  86037. })(BABYLON || (BABYLON = {}));
  86038. //# sourceMappingURL=babylon.dds.js.map
  86039. var BABYLON;
  86040. (function (BABYLON) {
  86041. /**
  86042. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86043. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86044. */
  86045. var KhronosTextureContainer = /** @class */ (function () {
  86046. /**
  86047. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86048. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86049. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86050. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86051. */
  86052. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86053. this.arrayBuffer = arrayBuffer;
  86054. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86055. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86056. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86057. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86058. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86059. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86060. BABYLON.Tools.Error("texture missing KTX identifier");
  86061. return;
  86062. }
  86063. // load the reset of the header in native 32 bit int
  86064. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86065. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86066. var oppositeEndianess = header[0] === 0x01020304;
  86067. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86068. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86069. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86070. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86071. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86072. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86073. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86074. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86075. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86076. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86077. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86078. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86079. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86080. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86081. if (this.glType !== 0) {
  86082. BABYLON.Tools.Error("only compressed formats currently supported");
  86083. return;
  86084. }
  86085. else {
  86086. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86087. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86088. }
  86089. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86090. BABYLON.Tools.Error("only 2D textures currently supported");
  86091. return;
  86092. }
  86093. if (this.numberOfArrayElements !== 0) {
  86094. BABYLON.Tools.Error("texture arrays not currently supported");
  86095. return;
  86096. }
  86097. if (this.numberOfFaces !== facesExpected) {
  86098. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86099. return;
  86100. }
  86101. // we now have a completely validated file, so could use existence of loadType as success
  86102. // would need to make this more elaborate & adjust checks above to support more than one load type
  86103. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86104. }
  86105. // not as fast hardware based, but will probably never need to use
  86106. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86107. return ((val & 0xFF) << 24)
  86108. | ((val & 0xFF00) << 8)
  86109. | ((val >> 8) & 0xFF00)
  86110. | ((val >> 24) & 0xFF);
  86111. };
  86112. /**
  86113. * It is assumed that the texture has already been created & is currently bound
  86114. */
  86115. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86116. switch (this.loadType) {
  86117. case KhronosTextureContainer.COMPRESSED_2D:
  86118. this._upload2DCompressedLevels(gl, loadMipmaps);
  86119. break;
  86120. case KhronosTextureContainer.TEX_2D:
  86121. case KhronosTextureContainer.COMPRESSED_3D:
  86122. case KhronosTextureContainer.TEX_3D:
  86123. }
  86124. };
  86125. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86126. // initialize width & height for level 1
  86127. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86128. var width = this.pixelWidth;
  86129. var height = this.pixelHeight;
  86130. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86131. for (var level = 0; level < mipmapCount; level++) {
  86132. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86133. for (var face = 0; face < this.numberOfFaces; face++) {
  86134. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86135. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86136. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86137. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86138. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86139. }
  86140. width = Math.max(1.0, width * 0.5);
  86141. height = Math.max(1.0, height * 0.5);
  86142. }
  86143. };
  86144. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86145. // load types
  86146. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86147. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86148. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86149. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86150. return KhronosTextureContainer;
  86151. }());
  86152. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86153. })(BABYLON || (BABYLON = {}));
  86154. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86155. var BABYLON;
  86156. (function (BABYLON) {
  86157. var Debug;
  86158. (function (Debug) {
  86159. /**
  86160. * Class used to render a debug view of a given skeleton
  86161. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86162. */
  86163. var SkeletonViewer = /** @class */ (function () {
  86164. /**
  86165. * Creates a new SkeletonViewer
  86166. * @param skeleton defines the skeleton to render
  86167. * @param mesh defines the mesh attached to the skeleton
  86168. * @param scene defines the hosting scene
  86169. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86170. * @param renderingGroupId defines the rendering group id to use with the viewer
  86171. */
  86172. function SkeletonViewer(
  86173. /** defines the skeleton to render */
  86174. skeleton,
  86175. /** defines the mesh attached to the skeleton */
  86176. mesh, scene,
  86177. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86178. autoUpdateBonesMatrices,
  86179. /** defines the rendering group id to use with the viewer */
  86180. renderingGroupId) {
  86181. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86182. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86183. this.skeleton = skeleton;
  86184. this.mesh = mesh;
  86185. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86186. this.renderingGroupId = renderingGroupId;
  86187. /** Gets or sets the color used to render the skeleton */
  86188. this.color = BABYLON.Color3.White();
  86189. this._debugLines = new Array();
  86190. this._isEnabled = false;
  86191. this._scene = scene;
  86192. this.update();
  86193. this._renderFunction = this.update.bind(this);
  86194. }
  86195. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86196. get: function () {
  86197. return this._isEnabled;
  86198. },
  86199. /** Gets or sets a boolean indicating if the viewer is enabled */
  86200. set: function (value) {
  86201. if (this._isEnabled === value) {
  86202. return;
  86203. }
  86204. this._isEnabled = value;
  86205. if (value) {
  86206. this._scene.registerBeforeRender(this._renderFunction);
  86207. }
  86208. else {
  86209. this._scene.unregisterBeforeRender(this._renderFunction);
  86210. }
  86211. },
  86212. enumerable: true,
  86213. configurable: true
  86214. });
  86215. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86216. if (x === void 0) { x = 0; }
  86217. if (y === void 0) { y = 0; }
  86218. if (z === void 0) { z = 0; }
  86219. var tmat = BABYLON.Tmp.Matrix[0];
  86220. var parentBone = bone.getParent();
  86221. tmat.copyFrom(bone.getLocalMatrix());
  86222. if (x !== 0 || y !== 0 || z !== 0) {
  86223. var tmat2 = BABYLON.Tmp.Matrix[1];
  86224. BABYLON.Matrix.IdentityToRef(tmat2);
  86225. tmat2.m[12] = x;
  86226. tmat2.m[13] = y;
  86227. tmat2.m[14] = z;
  86228. tmat2.multiplyToRef(tmat, tmat);
  86229. }
  86230. if (parentBone) {
  86231. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86232. }
  86233. tmat.multiplyToRef(meshMat, tmat);
  86234. position.x = tmat.m[12];
  86235. position.y = tmat.m[13];
  86236. position.z = tmat.m[14];
  86237. };
  86238. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86239. var len = bones.length;
  86240. var meshPos = this.mesh.position;
  86241. for (var i = 0; i < len; i++) {
  86242. var bone = bones[i];
  86243. var points = this._debugLines[i];
  86244. if (!points) {
  86245. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86246. this._debugLines[i] = points;
  86247. }
  86248. this._getBonePosition(points[0], bone, meshMat);
  86249. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86250. points[0].subtractInPlace(meshPos);
  86251. points[1].subtractInPlace(meshPos);
  86252. }
  86253. };
  86254. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86255. var len = bones.length;
  86256. var boneNum = 0;
  86257. var meshPos = this.mesh.position;
  86258. for (var i = len - 1; i >= 0; i--) {
  86259. var childBone = bones[i];
  86260. var parentBone = childBone.getParent();
  86261. if (!parentBone) {
  86262. continue;
  86263. }
  86264. var points = this._debugLines[boneNum];
  86265. if (!points) {
  86266. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86267. this._debugLines[boneNum] = points;
  86268. }
  86269. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86270. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86271. points[0].subtractInPlace(meshPos);
  86272. points[1].subtractInPlace(meshPos);
  86273. boneNum++;
  86274. }
  86275. };
  86276. /** Update the viewer to sync with current skeleton state */
  86277. SkeletonViewer.prototype.update = function () {
  86278. if (this.autoUpdateBonesMatrices) {
  86279. this.skeleton.computeAbsoluteTransforms();
  86280. }
  86281. if (this.skeleton.bones[0].length === undefined) {
  86282. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86283. }
  86284. else {
  86285. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86286. }
  86287. if (!this._debugMesh) {
  86288. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86289. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86290. }
  86291. else {
  86292. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86293. }
  86294. this._debugMesh.position.copyFrom(this.mesh.position);
  86295. this._debugMesh.color = this.color;
  86296. };
  86297. /** Release associated resources */
  86298. SkeletonViewer.prototype.dispose = function () {
  86299. if (this._debugMesh) {
  86300. this.isEnabled = false;
  86301. this._debugMesh.dispose();
  86302. this._debugMesh = null;
  86303. }
  86304. };
  86305. return SkeletonViewer;
  86306. }());
  86307. Debug.SkeletonViewer = SkeletonViewer;
  86308. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86309. })(BABYLON || (BABYLON = {}));
  86310. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86311. /**
  86312. * Module Debug contains the (visual) components to debug a scene correctly
  86313. */
  86314. var BABYLON;
  86315. (function (BABYLON) {
  86316. var Debug;
  86317. (function (Debug) {
  86318. /**
  86319. * The Axes viewer will show 3 axes in a specific point in space
  86320. */
  86321. var AxesViewer = /** @class */ (function () {
  86322. /**
  86323. * Creates a new AxesViewer
  86324. * @param scene defines the hosting scene
  86325. * @param scaleLines defines a number used to scale line length (1 by default)
  86326. */
  86327. function AxesViewer(scene, scaleLines) {
  86328. if (scaleLines === void 0) { scaleLines = 1; }
  86329. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86330. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86331. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86332. /**
  86333. * Gets or sets a number used to scale line length
  86334. */
  86335. this.scaleLines = 1;
  86336. this.scaleLines = scaleLines;
  86337. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86338. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86339. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86340. this._xmesh.renderingGroupId = 2;
  86341. this._ymesh.renderingGroupId = 2;
  86342. this._zmesh.renderingGroupId = 2;
  86343. this._xmesh.material.checkReadyOnlyOnce = true;
  86344. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86345. this._ymesh.material.checkReadyOnlyOnce = true;
  86346. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86347. this._zmesh.material.checkReadyOnlyOnce = true;
  86348. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86349. this.scene = scene;
  86350. }
  86351. /**
  86352. * Force the viewer to update
  86353. * @param position defines the position of the viewer
  86354. * @param xaxis defines the x axis of the viewer
  86355. * @param yaxis defines the y axis of the viewer
  86356. * @param zaxis defines the z axis of the viewer
  86357. */
  86358. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86359. var scaleLines = this.scaleLines;
  86360. if (this._xmesh) {
  86361. this._xmesh.position.copyFrom(position);
  86362. }
  86363. if (this._ymesh) {
  86364. this._ymesh.position.copyFrom(position);
  86365. }
  86366. if (this._zmesh) {
  86367. this._zmesh.position.copyFrom(position);
  86368. }
  86369. var point2 = this._xline[1];
  86370. point2.x = xaxis.x * scaleLines;
  86371. point2.y = xaxis.y * scaleLines;
  86372. point2.z = xaxis.z * scaleLines;
  86373. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86374. point2 = this._yline[1];
  86375. point2.x = yaxis.x * scaleLines;
  86376. point2.y = yaxis.y * scaleLines;
  86377. point2.z = yaxis.z * scaleLines;
  86378. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86379. point2 = this._zline[1];
  86380. point2.x = zaxis.x * scaleLines;
  86381. point2.y = zaxis.y * scaleLines;
  86382. point2.z = zaxis.z * scaleLines;
  86383. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86384. };
  86385. /** Releases resources */
  86386. AxesViewer.prototype.dispose = function () {
  86387. if (this._xmesh) {
  86388. this._xmesh.dispose();
  86389. }
  86390. if (this._ymesh) {
  86391. this._ymesh.dispose();
  86392. }
  86393. if (this._zmesh) {
  86394. this._zmesh.dispose();
  86395. }
  86396. this._xmesh = null;
  86397. this._ymesh = null;
  86398. this._zmesh = null;
  86399. this.scene = null;
  86400. };
  86401. return AxesViewer;
  86402. }());
  86403. Debug.AxesViewer = AxesViewer;
  86404. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86405. })(BABYLON || (BABYLON = {}));
  86406. //# sourceMappingURL=babylon.axesViewer.js.map
  86407. var BABYLON;
  86408. (function (BABYLON) {
  86409. var Debug;
  86410. (function (Debug) {
  86411. /**
  86412. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86413. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86414. */
  86415. var BoneAxesViewer = /** @class */ (function (_super) {
  86416. __extends(BoneAxesViewer, _super);
  86417. /**
  86418. * Creates a new BoneAxesViewer
  86419. * @param scene defines the hosting scene
  86420. * @param bone defines the target bone
  86421. * @param mesh defines the target mesh
  86422. * @param scaleLines defines a scaling factor for line length (1 by default)
  86423. */
  86424. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86425. if (scaleLines === void 0) { scaleLines = 1; }
  86426. var _this = _super.call(this, scene, scaleLines) || this;
  86427. /** Gets current position */
  86428. _this.pos = BABYLON.Vector3.Zero();
  86429. /** Gets direction of X axis */
  86430. _this.xaxis = BABYLON.Vector3.Zero();
  86431. /** Gets direction of Y axis */
  86432. _this.yaxis = BABYLON.Vector3.Zero();
  86433. /** Gets direction of Z axis */
  86434. _this.zaxis = BABYLON.Vector3.Zero();
  86435. _this.mesh = mesh;
  86436. _this.bone = bone;
  86437. return _this;
  86438. }
  86439. /**
  86440. * Force the viewer to update
  86441. */
  86442. BoneAxesViewer.prototype.update = function () {
  86443. if (!this.mesh || !this.bone) {
  86444. return;
  86445. }
  86446. var bone = this.bone;
  86447. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86448. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86449. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86450. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86451. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86452. };
  86453. /** Releases resources */
  86454. BoneAxesViewer.prototype.dispose = function () {
  86455. if (this.mesh) {
  86456. this.mesh = null;
  86457. this.bone = null;
  86458. _super.prototype.dispose.call(this);
  86459. }
  86460. };
  86461. return BoneAxesViewer;
  86462. }(Debug.AxesViewer));
  86463. Debug.BoneAxesViewer = BoneAxesViewer;
  86464. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86465. })(BABYLON || (BABYLON = {}));
  86466. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86467. var BABYLON;
  86468. (function (BABYLON) {
  86469. var RayHelper = /** @class */ (function () {
  86470. function RayHelper(ray) {
  86471. this.ray = ray;
  86472. }
  86473. RayHelper.CreateAndShow = function (ray, scene, color) {
  86474. var helper = new RayHelper(ray);
  86475. helper.show(scene, color);
  86476. return helper;
  86477. };
  86478. RayHelper.prototype.show = function (scene, color) {
  86479. if (!this._renderFunction && this.ray) {
  86480. var ray = this.ray;
  86481. this._renderFunction = this._render.bind(this);
  86482. this._scene = scene;
  86483. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86484. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86485. if (this._renderFunction) {
  86486. this._scene.registerBeforeRender(this._renderFunction);
  86487. }
  86488. }
  86489. if (color && this._renderLine) {
  86490. this._renderLine.color.copyFrom(color);
  86491. }
  86492. };
  86493. RayHelper.prototype.hide = function () {
  86494. if (this._renderFunction && this._scene) {
  86495. this._scene.unregisterBeforeRender(this._renderFunction);
  86496. this._scene = null;
  86497. this._renderFunction = null;
  86498. if (this._renderLine) {
  86499. this._renderLine.dispose();
  86500. this._renderLine = null;
  86501. }
  86502. this._renderPoints = [];
  86503. }
  86504. };
  86505. RayHelper.prototype._render = function () {
  86506. var ray = this.ray;
  86507. if (!ray) {
  86508. return;
  86509. }
  86510. var point = this._renderPoints[1];
  86511. var len = Math.min(ray.length, 1000000);
  86512. point.copyFrom(ray.direction);
  86513. point.scaleInPlace(len);
  86514. point.addInPlace(ray.origin);
  86515. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86516. };
  86517. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86518. this._attachedToMesh = mesh;
  86519. var ray = this.ray;
  86520. if (!ray) {
  86521. return;
  86522. }
  86523. if (!ray.direction) {
  86524. ray.direction = BABYLON.Vector3.Zero();
  86525. }
  86526. if (!ray.origin) {
  86527. ray.origin = BABYLON.Vector3.Zero();
  86528. }
  86529. if (length) {
  86530. ray.length = length;
  86531. }
  86532. if (!meshSpaceOrigin) {
  86533. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86534. }
  86535. if (!meshSpaceDirection) {
  86536. // -1 so that this will work with Mesh.lookAt
  86537. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86538. }
  86539. if (!this._meshSpaceDirection) {
  86540. this._meshSpaceDirection = meshSpaceDirection.clone();
  86541. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86542. }
  86543. else {
  86544. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86545. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86546. }
  86547. if (!this._updateToMeshFunction) {
  86548. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86549. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86550. }
  86551. this._updateToMesh();
  86552. };
  86553. RayHelper.prototype.detachFromMesh = function () {
  86554. if (this._attachedToMesh) {
  86555. if (this._updateToMeshFunction) {
  86556. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86557. }
  86558. this._attachedToMesh = null;
  86559. this._updateToMeshFunction = null;
  86560. }
  86561. };
  86562. RayHelper.prototype._updateToMesh = function () {
  86563. var ray = this.ray;
  86564. if (!this._attachedToMesh || !ray) {
  86565. return;
  86566. }
  86567. if (this._attachedToMesh._isDisposed) {
  86568. this.detachFromMesh();
  86569. return;
  86570. }
  86571. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86572. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86573. };
  86574. RayHelper.prototype.dispose = function () {
  86575. this.hide();
  86576. this.detachFromMesh();
  86577. this.ray = null;
  86578. };
  86579. return RayHelper;
  86580. }());
  86581. BABYLON.RayHelper = RayHelper;
  86582. })(BABYLON || (BABYLON = {}));
  86583. //# sourceMappingURL=babylon.rayHelper.js.map
  86584. var BABYLON;
  86585. (function (BABYLON) {
  86586. // load the inspector using require, if not present in the global namespace.
  86587. var DebugLayer = /** @class */ (function () {
  86588. function DebugLayer(scene) {
  86589. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86590. this._scene = scene;
  86591. // load inspector using require, if it doesn't exist on the global namespace.
  86592. }
  86593. /** Creates the inspector window. */
  86594. DebugLayer.prototype._createInspector = function (config) {
  86595. if (config === void 0) { config = {}; }
  86596. var popup = config.popup || false;
  86597. var initialTab = config.initialTab || 0;
  86598. var parentElement = config.parentElement || null;
  86599. if (!this._inspector) {
  86600. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86601. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86602. } // else nothing to do,; instance is already existing
  86603. };
  86604. DebugLayer.prototype.isVisible = function () {
  86605. if (!this._inspector) {
  86606. return false;
  86607. }
  86608. return true;
  86609. };
  86610. DebugLayer.prototype.hide = function () {
  86611. if (this._inspector) {
  86612. try {
  86613. this._inspector.dispose();
  86614. }
  86615. catch (e) {
  86616. // If the inspector has been removed directly from the inspector tool
  86617. }
  86618. this._inspector = null;
  86619. }
  86620. };
  86621. /**
  86622. *
  86623. * Launch the debugLayer.
  86624. *
  86625. * initialTab:
  86626. * | Value | Tab Name |
  86627. * | --- | --- |
  86628. * | 0 | Scene |
  86629. * | 1 | Console |
  86630. * | 2 | Stats |
  86631. * | 3 | Textures |
  86632. * | 4 | Mesh |
  86633. * | 5 | Light |
  86634. * | 6 | Material |
  86635. * | 7 | GLTF |
  86636. * | 8 | GUI |
  86637. * | 9 | Physics |
  86638. * | 10 | Camera |
  86639. * | 11 | Audio |
  86640. *
  86641. */
  86642. DebugLayer.prototype.show = function (config) {
  86643. if (config === void 0) { config = {}; }
  86644. if (typeof this.BJSINSPECTOR == 'undefined') {
  86645. // Load inspector and add it to the DOM
  86646. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86647. }
  86648. else {
  86649. // Otherwise creates the inspector
  86650. this._createInspector(config);
  86651. }
  86652. };
  86653. /**
  86654. * Gets the active tab
  86655. * @return the index of the active tab or -1 if the inspector is hidden
  86656. */
  86657. DebugLayer.prototype.getActiveTab = function () {
  86658. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86659. };
  86660. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86661. return DebugLayer;
  86662. }());
  86663. BABYLON.DebugLayer = DebugLayer;
  86664. })(BABYLON || (BABYLON = {}));
  86665. //# sourceMappingURL=babylon.debugLayer.js.map
  86666. var BABYLON;
  86667. (function (BABYLON) {
  86668. var Debug;
  86669. (function (Debug) {
  86670. /**
  86671. * Used to show the physics impostor around the specific mesh
  86672. */
  86673. var PhysicsViewer = /** @class */ (function () {
  86674. /**
  86675. * Creates a new PhysicsViewer
  86676. * @param scene defines the hosting scene
  86677. */
  86678. function PhysicsViewer(scene) {
  86679. /** @hidden */
  86680. this._impostors = [];
  86681. /** @hidden */
  86682. this._meshes = [];
  86683. /** @hidden */
  86684. this._numMeshes = 0;
  86685. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86686. var physicEngine = this._scene.getPhysicsEngine();
  86687. if (physicEngine) {
  86688. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86689. }
  86690. }
  86691. /** @hidden */
  86692. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86693. var plugin = this._physicsEnginePlugin;
  86694. for (var i = 0; i < this._numMeshes; i++) {
  86695. var impostor = this._impostors[i];
  86696. if (!impostor) {
  86697. continue;
  86698. }
  86699. if (impostor.isDisposed) {
  86700. this.hideImpostor(this._impostors[i--]);
  86701. }
  86702. else {
  86703. var mesh = this._meshes[i];
  86704. if (mesh && plugin) {
  86705. plugin.syncMeshWithImpostor(mesh, impostor);
  86706. }
  86707. }
  86708. }
  86709. };
  86710. /**
  86711. * Renders a specified physic impostor
  86712. * @param impostor defines the impostor to render
  86713. */
  86714. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86715. if (!this._scene) {
  86716. return;
  86717. }
  86718. for (var i = 0; i < this._numMeshes; i++) {
  86719. if (this._impostors[i] == impostor) {
  86720. return;
  86721. }
  86722. }
  86723. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86724. if (debugMesh) {
  86725. this._impostors[this._numMeshes] = impostor;
  86726. this._meshes[this._numMeshes] = debugMesh;
  86727. if (this._numMeshes === 0) {
  86728. this._renderFunction = this._updateDebugMeshes.bind(this);
  86729. this._scene.registerBeforeRender(this._renderFunction);
  86730. }
  86731. this._numMeshes++;
  86732. }
  86733. };
  86734. /**
  86735. * Hides a specified physic impostor
  86736. * @param impostor defines the impostor to hide
  86737. */
  86738. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86739. if (!impostor || !this._scene) {
  86740. return;
  86741. }
  86742. var removed = false;
  86743. for (var i = 0; i < this._numMeshes; i++) {
  86744. if (this._impostors[i] == impostor) {
  86745. var mesh = this._meshes[i];
  86746. if (!mesh) {
  86747. continue;
  86748. }
  86749. this._scene.removeMesh(mesh);
  86750. mesh.dispose();
  86751. this._numMeshes--;
  86752. if (this._numMeshes > 0) {
  86753. this._meshes[i] = this._meshes[this._numMeshes];
  86754. this._impostors[i] = this._impostors[this._numMeshes];
  86755. this._meshes[this._numMeshes] = null;
  86756. this._impostors[this._numMeshes] = null;
  86757. }
  86758. else {
  86759. this._meshes[0] = null;
  86760. this._impostors[0] = null;
  86761. }
  86762. removed = true;
  86763. break;
  86764. }
  86765. }
  86766. if (removed && this._numMeshes === 0) {
  86767. this._scene.unregisterBeforeRender(this._renderFunction);
  86768. }
  86769. };
  86770. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86771. if (!this._debugMaterial) {
  86772. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86773. this._debugMaterial.wireframe = true;
  86774. }
  86775. return this._debugMaterial;
  86776. };
  86777. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86778. if (!this._debugBoxMesh) {
  86779. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86780. this._debugBoxMesh.renderingGroupId = 1;
  86781. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86782. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86783. scene.removeMesh(this._debugBoxMesh);
  86784. }
  86785. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86786. };
  86787. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86788. if (!this._debugSphereMesh) {
  86789. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86790. this._debugSphereMesh.renderingGroupId = 1;
  86791. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86792. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86793. scene.removeMesh(this._debugSphereMesh);
  86794. }
  86795. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86796. };
  86797. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86798. var mesh = null;
  86799. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86800. mesh = this._getDebugBoxMesh(scene);
  86801. impostor.getBoxSizeToRef(mesh.scaling);
  86802. }
  86803. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86804. mesh = this._getDebugSphereMesh(scene);
  86805. var radius = impostor.getRadius();
  86806. mesh.scaling.x = radius * 2;
  86807. mesh.scaling.y = radius * 2;
  86808. mesh.scaling.z = radius * 2;
  86809. }
  86810. return mesh;
  86811. };
  86812. /** Releases all resources */
  86813. PhysicsViewer.prototype.dispose = function () {
  86814. for (var i = 0; i < this._numMeshes; i++) {
  86815. this.hideImpostor(this._impostors[i]);
  86816. }
  86817. if (this._debugBoxMesh) {
  86818. this._debugBoxMesh.dispose();
  86819. }
  86820. if (this._debugSphereMesh) {
  86821. this._debugSphereMesh.dispose();
  86822. }
  86823. if (this._debugMaterial) {
  86824. this._debugMaterial.dispose();
  86825. }
  86826. this._impostors.length = 0;
  86827. this._scene = null;
  86828. this._physicsEnginePlugin = null;
  86829. };
  86830. return PhysicsViewer;
  86831. }());
  86832. Debug.PhysicsViewer = PhysicsViewer;
  86833. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86834. })(BABYLON || (BABYLON = {}));
  86835. //# sourceMappingURL=babylon.physicsViewer.js.map
  86836. var BABYLON;
  86837. (function (BABYLON) {
  86838. var BoundingBoxRenderer = /** @class */ (function () {
  86839. function BoundingBoxRenderer(scene) {
  86840. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86841. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86842. this.showBackLines = true;
  86843. this.renderList = new BABYLON.SmartArray(32);
  86844. this._vertexBuffers = {};
  86845. this._scene = scene;
  86846. }
  86847. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86848. if (this._colorShader) {
  86849. return;
  86850. }
  86851. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86852. attributes: [BABYLON.VertexBuffer.PositionKind],
  86853. uniforms: ["world", "viewProjection", "color"]
  86854. });
  86855. var engine = this._scene.getEngine();
  86856. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86857. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86858. this._createIndexBuffer();
  86859. };
  86860. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86861. var engine = this._scene.getEngine();
  86862. 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]);
  86863. };
  86864. BoundingBoxRenderer.prototype._rebuild = function () {
  86865. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86866. if (vb) {
  86867. vb._rebuild();
  86868. }
  86869. this._createIndexBuffer();
  86870. };
  86871. BoundingBoxRenderer.prototype.reset = function () {
  86872. this.renderList.reset();
  86873. };
  86874. BoundingBoxRenderer.prototype.render = function () {
  86875. if (this.renderList.length === 0) {
  86876. return;
  86877. }
  86878. this._prepareRessources();
  86879. if (!this._colorShader.isReady()) {
  86880. return;
  86881. }
  86882. var engine = this._scene.getEngine();
  86883. engine.setDepthWrite(false);
  86884. this._colorShader._preBind();
  86885. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86886. var boundingBox = this.renderList.data[boundingBoxIndex];
  86887. var min = boundingBox.minimum;
  86888. var max = boundingBox.maximum;
  86889. var diff = max.subtract(min);
  86890. var median = min.add(diff.scale(0.5));
  86891. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86892. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86893. .multiply(boundingBox.getWorldMatrix());
  86894. // VBOs
  86895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86896. if (this.showBackLines) {
  86897. // Back
  86898. engine.setDepthFunctionToGreaterOrEqual();
  86899. this._scene.resetCachedMaterial();
  86900. this._colorShader.setColor4("color", this.backColor.toColor4());
  86901. this._colorShader.bind(worldMatrix);
  86902. // Draw order
  86903. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86904. }
  86905. // Front
  86906. engine.setDepthFunctionToLess();
  86907. this._scene.resetCachedMaterial();
  86908. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86909. this._colorShader.bind(worldMatrix);
  86910. // Draw order
  86911. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86912. }
  86913. this._colorShader.unbind();
  86914. engine.setDepthFunctionToLessOrEqual();
  86915. engine.setDepthWrite(true);
  86916. };
  86917. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86918. this._prepareRessources();
  86919. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86920. return;
  86921. }
  86922. var engine = this._scene.getEngine();
  86923. engine.setDepthWrite(false);
  86924. engine.setColorWrite(false);
  86925. this._colorShader._preBind();
  86926. var boundingBox = mesh._boundingInfo.boundingBox;
  86927. var min = boundingBox.minimum;
  86928. var max = boundingBox.maximum;
  86929. var diff = max.subtract(min);
  86930. var median = min.add(diff.scale(0.5));
  86931. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86932. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86933. .multiply(boundingBox.getWorldMatrix());
  86934. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86935. engine.setDepthFunctionToLess();
  86936. this._scene.resetCachedMaterial();
  86937. this._colorShader.bind(worldMatrix);
  86938. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86939. this._colorShader.unbind();
  86940. engine.setDepthFunctionToLessOrEqual();
  86941. engine.setDepthWrite(true);
  86942. engine.setColorWrite(true);
  86943. };
  86944. BoundingBoxRenderer.prototype.dispose = function () {
  86945. if (!this._colorShader) {
  86946. return;
  86947. }
  86948. this.renderList.dispose();
  86949. this._colorShader.dispose();
  86950. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86951. if (buffer) {
  86952. buffer.dispose();
  86953. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86954. }
  86955. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86956. };
  86957. return BoundingBoxRenderer;
  86958. }());
  86959. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86960. })(BABYLON || (BABYLON = {}));
  86961. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86962. var BABYLON;
  86963. (function (BABYLON) {
  86964. /**
  86965. * Renders a layer on top of an existing scene
  86966. */
  86967. var UtilityLayerRenderer = /** @class */ (function () {
  86968. /**
  86969. * Instantiates a UtilityLayerRenderer
  86970. * @param originalScene the original scene that will be rendered on top of
  86971. */
  86972. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86973. var _this = this;
  86974. this.originalScene = originalScene;
  86975. this._pointerCaptures = {};
  86976. this._lastPointerEvents = {};
  86977. /**
  86978. * If the utility layer should automatically be rendered on top of existing scene
  86979. */
  86980. this.shouldRender = true;
  86981. /**
  86982. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  86983. */
  86984. this.onlyCheckPointerDownEvents = true;
  86985. /**
  86986. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  86987. */
  86988. this.processAllEvents = false;
  86989. /**
  86990. * Observable raised when the pointer move from the utility layer scene to the main scene
  86991. */
  86992. this.onPointerOutObservable = new BABYLON.Observable();
  86993. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86994. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86995. originalScene.getEngine().scenes.pop();
  86996. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  86997. this.utilityLayerScene.detachControl();
  86998. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  86999. if (!_this.processAllEvents) {
  87000. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87001. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87002. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87003. return;
  87004. }
  87005. }
  87006. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87007. if (!prePointerInfo.ray && utilityScenePick) {
  87008. prePointerInfo.ray = utilityScenePick.ray;
  87009. }
  87010. // always fire the prepointer oversvable
  87011. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87012. // allow every non pointer down event to flow to the utility layer
  87013. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87014. if (!prePointerInfo.skipOnPointerObservable) {
  87015. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87016. }
  87017. return;
  87018. }
  87019. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87020. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87021. if (utilityScenePick && utilityScenePick.hit) {
  87022. if (!prePointerInfo.skipOnPointerObservable) {
  87023. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87024. }
  87025. prePointerInfo.skipOnPointerObservable = true;
  87026. }
  87027. }
  87028. else {
  87029. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87030. var pointerEvent = (prePointerInfo.event);
  87031. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87032. if (originalScenePick && utilityScenePick) {
  87033. if (utilityScenePick.distance === 0) {
  87034. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87035. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87036. }
  87037. }
  87038. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87039. if (!prePointerInfo.skipOnPointerObservable) {
  87040. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87041. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87042. }
  87043. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87044. }
  87045. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87046. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87047. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87048. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87049. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87050. }
  87051. }
  87052. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87053. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87054. }
  87055. }
  87056. }
  87057. });
  87058. // Render directly on top of existing scene without clearing
  87059. this.utilityLayerScene.autoClear = false;
  87060. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87061. if (_this.shouldRender) {
  87062. _this.render();
  87063. }
  87064. });
  87065. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87066. _this.dispose();
  87067. });
  87068. this._updateCamera();
  87069. }
  87070. /**
  87071. * Renders the utility layers scene on top of the original scene
  87072. */
  87073. UtilityLayerRenderer.prototype.render = function () {
  87074. this._updateCamera();
  87075. this.utilityLayerScene.render(false);
  87076. };
  87077. /**
  87078. * Disposes of the renderer
  87079. */
  87080. UtilityLayerRenderer.prototype.dispose = function () {
  87081. this.onPointerOutObservable.clear();
  87082. if (this._afterRenderObserver) {
  87083. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87084. }
  87085. if (this._sceneDisposeObserver) {
  87086. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87087. }
  87088. if (this._originalPointerObserver) {
  87089. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87090. }
  87091. this.utilityLayerScene.dispose();
  87092. };
  87093. UtilityLayerRenderer.prototype._updateCamera = function () {
  87094. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87095. };
  87096. return UtilityLayerRenderer;
  87097. }());
  87098. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87099. })(BABYLON || (BABYLON = {}));
  87100. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87101. var BABYLON;
  87102. (function (BABYLON) {
  87103. /**
  87104. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87105. */
  87106. var PointerDragBehavior = /** @class */ (function () {
  87107. /**
  87108. * Creates a pointer drag behavior that can be attached to a mesh
  87109. * @param options The drag axis or normal of the plane that will be dragged across.
  87110. */
  87111. function PointerDragBehavior(options) {
  87112. this.options = options;
  87113. this._draggingID = -1;
  87114. /**
  87115. * Fires each time the attached mesh is dragged with the pointer
  87116. */
  87117. this.onDragObservable = new BABYLON.Observable();
  87118. /**
  87119. * Fires each time a drag begins (eg. mouse down on mesh)
  87120. */
  87121. this.onDragStartObservable = new BABYLON.Observable();
  87122. /**
  87123. * Fires each time a drag ends (eg. mouse release after drag)
  87124. */
  87125. this.onDragEndObservable = new BABYLON.Observable();
  87126. /**
  87127. * If the attached mesh should be moved when dragged
  87128. */
  87129. this.moveAttached = true;
  87130. /**
  87131. * Mesh with the position where the drag plane should be placed
  87132. */
  87133. this._dragPlaneParent = null;
  87134. /**
  87135. * If the drag behavior will react to drag events
  87136. */
  87137. this.enabled = true;
  87138. var optionCount = 0;
  87139. if (options.dragAxis) {
  87140. optionCount++;
  87141. }
  87142. if (options.dragPlaneNormal) {
  87143. optionCount++;
  87144. }
  87145. if (optionCount > 1) {
  87146. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87147. }
  87148. if (optionCount < 1) {
  87149. throw "At least one drag mode option must be specified";
  87150. }
  87151. }
  87152. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87153. /**
  87154. * The name of the behavior
  87155. */
  87156. get: function () {
  87157. return "PointerDrag";
  87158. },
  87159. enumerable: true,
  87160. configurable: true
  87161. });
  87162. /**
  87163. * Initializes the behavior
  87164. */
  87165. PointerDragBehavior.prototype.init = function () { };
  87166. /**
  87167. * Attaches the drag behavior the passed in mesh
  87168. * @param ownerNode The mesh that will be dragged around once attached
  87169. */
  87170. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87171. var _this = this;
  87172. this._scene = ownerNode.getScene();
  87173. this._attachedNode = ownerNode;
  87174. // Initialize drag plane to not interfere with existing scene
  87175. if (!PointerDragBehavior._planeScene) {
  87176. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87177. this._scene.getEngine().scenes.pop();
  87178. }
  87179. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87180. // State of the drag
  87181. var dragging = false;
  87182. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87183. var delta = new BABYLON.Vector3(0, 0, 0);
  87184. var pickPredicate = function (m) {
  87185. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87186. };
  87187. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87188. if (!_this.enabled) {
  87189. return;
  87190. }
  87191. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87192. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87193. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87194. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87195. if (pickedPoint) {
  87196. dragging = true;
  87197. _this._draggingID = pointerInfo.event.pointerId;
  87198. lastPosition.copyFrom(pickedPoint);
  87199. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87200. }
  87201. }
  87202. }
  87203. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87204. if (_this._draggingID == pointerInfo.event.pointerId) {
  87205. dragging = false;
  87206. _this._draggingID = -1;
  87207. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87208. }
  87209. }
  87210. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87211. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87212. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87213. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87214. if (pickedPoint) {
  87215. // depending on the drag mode option drag accordingly
  87216. if (_this.options.dragAxis) {
  87217. //get the closest point on the dragaxis from the selected mesh to the picked point location
  87218. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  87219. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  87220. }
  87221. else {
  87222. pickedPoint.subtractToRef(lastPosition, delta);
  87223. }
  87224. if (_this.moveAttached) {
  87225. _this._attachedNode.position.addInPlace(delta);
  87226. }
  87227. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  87228. lastPosition.copyFrom(pickedPoint);
  87229. }
  87230. }
  87231. }
  87232. });
  87233. };
  87234. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87235. var _this = this;
  87236. if (!ray) {
  87237. return null;
  87238. }
  87239. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87240. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87241. return pickResult.pickedPoint;
  87242. }
  87243. else {
  87244. return null;
  87245. }
  87246. };
  87247. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87248. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87249. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  87250. if (this.options.dragAxis) {
  87251. var camPos = ray.origin;
  87252. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87253. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  87254. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  87255. // Get perpendicular line from direction to camera and drag axis
  87256. var lineA = pointB.subtract(pointA);
  87257. var lineB = pointC.subtract(pointA);
  87258. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87259. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87260. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87261. this._dragPlane.position.copyFrom(pointA);
  87262. this._dragPlane.lookAt(pointA.add(norm));
  87263. }
  87264. else if (this.options.dragPlaneNormal) {
  87265. this._dragPlane.position.copyFrom(pointA);
  87266. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  87267. }
  87268. this._dragPlane.computeWorldMatrix(true);
  87269. };
  87270. /**
  87271. * Detaches the behavior from the mesh
  87272. */
  87273. PointerDragBehavior.prototype.detach = function () {
  87274. if (this._pointerObserver) {
  87275. this._scene.onPointerObservable.remove(this._pointerObserver);
  87276. }
  87277. };
  87278. return PointerDragBehavior;
  87279. }());
  87280. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87281. })(BABYLON || (BABYLON = {}));
  87282. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87283. var BABYLON;
  87284. (function (BABYLON) {
  87285. /**
  87286. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87287. */
  87288. var Gizmo = /** @class */ (function () {
  87289. /**
  87290. * Creates a gizmo
  87291. * @param gizmoLayer The utility layer the gizmo will be added to
  87292. */
  87293. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87294. var _this = this;
  87295. this.gizmoLayer = gizmoLayer;
  87296. this._interactionsEnabled = true;
  87297. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87298. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87299. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87300. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87301. _this._rootMesh.scaling.set(dist, dist, dist);
  87302. }
  87303. if (_this.attachedMesh) {
  87304. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87305. }
  87306. });
  87307. }
  87308. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87309. };
  87310. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87311. get: function () {
  87312. return this._interactionsEnabled;
  87313. },
  87314. /**
  87315. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87316. */
  87317. set: function (value) {
  87318. this._interactionsEnabled = value;
  87319. this._onInteractionsEnabledChanged(value);
  87320. },
  87321. enumerable: true,
  87322. configurable: true
  87323. });
  87324. /**
  87325. * Disposes of the gizmo
  87326. */
  87327. Gizmo.prototype.dispose = function () {
  87328. this._rootMesh.dispose();
  87329. if (this._beforeRenderObserver) {
  87330. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87331. }
  87332. };
  87333. return Gizmo;
  87334. }());
  87335. BABYLON.Gizmo = Gizmo;
  87336. })(BABYLON || (BABYLON = {}));
  87337. //# sourceMappingURL=babylon.gizmo.js.map
  87338. var BABYLON;
  87339. (function (BABYLON) {
  87340. /**
  87341. * Single axis drag gizmo
  87342. */
  87343. var AxisDragGizmo = /** @class */ (function (_super) {
  87344. __extends(AxisDragGizmo, _super);
  87345. /**
  87346. * Creates an AxisDragGizmo
  87347. * @param gizmoLayer The utility layer the gizmo will be added to
  87348. * @param dragAxis The axis which the gizmo will be able to drag on
  87349. * @param color The color of the gizmo
  87350. */
  87351. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87352. var _this = _super.call(this, gizmoLayer) || this;
  87353. // Create Material
  87354. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87355. coloredMaterial.disableLighting = true;
  87356. coloredMaterial.emissiveColor = color;
  87357. // Build mesh on root node
  87358. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87359. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87360. _this._rootMesh.addChild(arrowMesh);
  87361. _this._rootMesh.addChild(arrowTail);
  87362. // Position arrow pointing in its drag axis
  87363. arrowMesh.scaling.scaleInPlace(0.1);
  87364. arrowMesh.material = coloredMaterial;
  87365. arrowMesh.rotation.x = Math.PI / 2;
  87366. arrowMesh.position.z += 0.3;
  87367. arrowTail.rotation.x = Math.PI / 2;
  87368. arrowTail.material = coloredMaterial;
  87369. arrowTail.position.z += 0.2;
  87370. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87371. // Add drag behavior to handle events when the gizmo is dragged
  87372. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87373. _this._dragBehavior.moveAttached = false;
  87374. _this._rootMesh.addBehavior(_this._dragBehavior);
  87375. _this._dragBehavior.onDragObservable.add(function (event) {
  87376. if (!_this.interactionsEnabled) {
  87377. return;
  87378. }
  87379. if (_this.attachedMesh) {
  87380. _this.attachedMesh.position.addInPlace(event.delta);
  87381. }
  87382. });
  87383. return _this;
  87384. }
  87385. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87386. this._dragBehavior.enabled = value;
  87387. };
  87388. /**
  87389. * Disposes of the gizmo
  87390. */
  87391. AxisDragGizmo.prototype.dispose = function () {
  87392. this._dragBehavior.detach();
  87393. _super.prototype.dispose.call(this);
  87394. };
  87395. return AxisDragGizmo;
  87396. }(BABYLON.Gizmo));
  87397. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87398. })(BABYLON || (BABYLON = {}));
  87399. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87400. var BABYLON;
  87401. (function (BABYLON) {
  87402. /**
  87403. * Single axis scale gizmo
  87404. */
  87405. var AxisScaleGizmo = /** @class */ (function (_super) {
  87406. __extends(AxisScaleGizmo, _super);
  87407. /**
  87408. * Creates an AxisScaleGizmo
  87409. * @param gizmoLayer The utility layer the gizmo will be added to
  87410. * @param dragAxis The axis which the gizmo will be able to scale on
  87411. * @param color The color of the gizmo
  87412. */
  87413. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87414. var _this = _super.call(this, gizmoLayer) || this;
  87415. // Create Material
  87416. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87417. coloredMaterial.disableLighting = true;
  87418. coloredMaterial.emissiveColor = color;
  87419. // Build mesh on root node
  87420. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87421. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87422. _this._rootMesh.addChild(arrowMesh);
  87423. _this._rootMesh.addChild(arrowTail);
  87424. // Position arrow pointing in its drag axis
  87425. arrowMesh.scaling.scaleInPlace(0.1);
  87426. arrowMesh.material = coloredMaterial;
  87427. arrowMesh.rotation.x = Math.PI / 2;
  87428. arrowMesh.position.z += 0.3;
  87429. arrowTail.rotation.x = Math.PI / 2;
  87430. arrowTail.material = coloredMaterial;
  87431. arrowTail.position.z += 0.2;
  87432. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87433. // Add drag behavior to handle events when the gizmo is dragged
  87434. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87435. _this._dragBehavior.moveAttached = false;
  87436. _this._rootMesh.addBehavior(_this._dragBehavior);
  87437. _this._dragBehavior.onDragObservable.add(function (event) {
  87438. if (!_this.interactionsEnabled) {
  87439. return;
  87440. }
  87441. if (_this.attachedMesh) {
  87442. _this.attachedMesh.scaling.addInPlace(event.delta);
  87443. }
  87444. });
  87445. return _this;
  87446. }
  87447. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87448. this._dragBehavior.enabled = value;
  87449. };
  87450. /**
  87451. * Disposes of the gizmo
  87452. */
  87453. AxisScaleGizmo.prototype.dispose = function () {
  87454. this._dragBehavior.detach();
  87455. _super.prototype.dispose.call(this);
  87456. };
  87457. return AxisScaleGizmo;
  87458. }(BABYLON.Gizmo));
  87459. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87460. })(BABYLON || (BABYLON = {}));
  87461. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87462. var BABYLON;
  87463. (function (BABYLON) {
  87464. /**
  87465. * Single plane rotation gizmo
  87466. */
  87467. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87468. __extends(PlaneRotationGizmo, _super);
  87469. /**
  87470. * Creates a PlaneRotationGizmo
  87471. * @param gizmoLayer The utility layer the gizmo will be added to
  87472. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87473. * @param color The color of the gizmo
  87474. */
  87475. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87476. var _this = _super.call(this, gizmoLayer) || this;
  87477. // Create Material
  87478. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87479. coloredMaterial.disableLighting = true;
  87480. coloredMaterial.emissiveColor = color;
  87481. // Build mesh on root node
  87482. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87483. _this._rootMesh.addChild(rotationMesh);
  87484. // Position arrow pointing in its drag axis
  87485. rotationMesh.scaling.scaleInPlace(0.1);
  87486. rotationMesh.material = coloredMaterial;
  87487. rotationMesh.rotation.x = Math.PI / 2;
  87488. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87489. // Add drag behavior to handle events when the gizmo is dragged
  87490. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87491. _this._dragBehavior.moveAttached = false;
  87492. _this._rootMesh.addBehavior(_this._dragBehavior);
  87493. var lastDragPosition = null;
  87494. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87495. if (!_this.interactionsEnabled) {
  87496. return;
  87497. }
  87498. lastDragPosition = e.dragPlanePoint;
  87499. });
  87500. _this._dragBehavior.onDragObservable.add(function (event) {
  87501. if (!_this.interactionsEnabled) {
  87502. return;
  87503. }
  87504. if (_this.attachedMesh && lastDragPosition) {
  87505. if (!_this.attachedMesh.rotationQuaternion) {
  87506. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87507. }
  87508. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87509. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87510. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87511. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87512. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87513. var angle = Math.atan2(cross.length(), dot);
  87514. var up = planeNormal.clone();
  87515. // Flip up vector depending on which side the camera is on
  87516. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87517. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87518. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87519. up.scaleInPlace(-1);
  87520. }
  87521. }
  87522. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87523. if (halfCircleSide)
  87524. angle = -angle;
  87525. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87526. var quaternionCoefficient = Math.sin(angle / 2);
  87527. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87528. // Rotate selected mesh quaternion over fixed axis
  87529. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87530. lastDragPosition = event.dragPlanePoint;
  87531. }
  87532. });
  87533. return _this;
  87534. }
  87535. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87536. this._dragBehavior.enabled = value;
  87537. };
  87538. /**
  87539. * Disposes of the gizmo
  87540. */
  87541. PlaneRotationGizmo.prototype.dispose = function () {
  87542. this._dragBehavior.detach();
  87543. _super.prototype.dispose.call(this);
  87544. };
  87545. return PlaneRotationGizmo;
  87546. }(BABYLON.Gizmo));
  87547. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87548. })(BABYLON || (BABYLON = {}));
  87549. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87550. var BABYLON;
  87551. (function (BABYLON) {
  87552. /**
  87553. * Gizmo that enables dragging a mesh along 3 axis
  87554. */
  87555. var PositionGizmo = /** @class */ (function (_super) {
  87556. __extends(PositionGizmo, _super);
  87557. /**
  87558. * Creates a PositionGizmo
  87559. * @param gizmoLayer The utility layer the gizmo will be added to
  87560. */
  87561. function PositionGizmo(gizmoLayer) {
  87562. var _this = _super.call(this, gizmoLayer) || this;
  87563. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87564. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87565. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87566. return _this;
  87567. }
  87568. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87569. set: function (mesh) {
  87570. this._xDrag.attachedMesh = mesh;
  87571. this._yDrag.attachedMesh = mesh;
  87572. this._zDrag.attachedMesh = mesh;
  87573. },
  87574. enumerable: true,
  87575. configurable: true
  87576. });
  87577. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87578. this._xDrag.interactionsEnabled = value;
  87579. this._yDrag.interactionsEnabled = value;
  87580. this._zDrag.interactionsEnabled = value;
  87581. };
  87582. /**
  87583. * Disposes of the gizmo
  87584. */
  87585. PositionGizmo.prototype.dispose = function () {
  87586. this._xDrag.dispose();
  87587. this._yDrag.dispose();
  87588. this._zDrag.dispose();
  87589. };
  87590. return PositionGizmo;
  87591. }(BABYLON.Gizmo));
  87592. BABYLON.PositionGizmo = PositionGizmo;
  87593. })(BABYLON || (BABYLON = {}));
  87594. //# sourceMappingURL=babylon.positionGizmo.js.map
  87595. var BABYLON;
  87596. (function (BABYLON) {
  87597. /**
  87598. * Gizmo that enables rotating a mesh along 3 axis
  87599. */
  87600. var RotationGizmo = /** @class */ (function (_super) {
  87601. __extends(RotationGizmo, _super);
  87602. /**
  87603. * Creates a RotationGizmo
  87604. * @param gizmoLayer The utility layer the gizmo will be added to
  87605. */
  87606. function RotationGizmo(gizmoLayer) {
  87607. var _this = _super.call(this, gizmoLayer) || this;
  87608. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87609. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87610. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87611. return _this;
  87612. }
  87613. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87614. set: function (mesh) {
  87615. this._xDrag.attachedMesh = mesh;
  87616. this._yDrag.attachedMesh = mesh;
  87617. this._zDrag.attachedMesh = mesh;
  87618. },
  87619. enumerable: true,
  87620. configurable: true
  87621. });
  87622. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87623. this._xDrag.interactionsEnabled = value;
  87624. this._yDrag.interactionsEnabled = value;
  87625. this._zDrag.interactionsEnabled = value;
  87626. };
  87627. /**
  87628. * Disposes of the gizmo
  87629. */
  87630. RotationGizmo.prototype.dispose = function () {
  87631. this._xDrag.dispose();
  87632. this._yDrag.dispose();
  87633. this._zDrag.dispose();
  87634. };
  87635. return RotationGizmo;
  87636. }(BABYLON.Gizmo));
  87637. BABYLON.RotationGizmo = RotationGizmo;
  87638. })(BABYLON || (BABYLON = {}));
  87639. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87640. var BABYLON;
  87641. (function (BABYLON) {
  87642. /**
  87643. * Gizmo that enables scaling a mesh along 3 axis
  87644. */
  87645. var ScaleGizmo = /** @class */ (function (_super) {
  87646. __extends(ScaleGizmo, _super);
  87647. /**
  87648. * Creates a ScaleGizmo
  87649. * @param gizmoLayer The utility layer the gizmo will be added to
  87650. */
  87651. function ScaleGizmo(gizmoLayer) {
  87652. var _this = _super.call(this, gizmoLayer) || this;
  87653. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87654. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87655. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87656. return _this;
  87657. }
  87658. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87659. set: function (mesh) {
  87660. this._xDrag.attachedMesh = mesh;
  87661. this._yDrag.attachedMesh = mesh;
  87662. this._zDrag.attachedMesh = mesh;
  87663. },
  87664. enumerable: true,
  87665. configurable: true
  87666. });
  87667. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87668. this._xDrag.interactionsEnabled = value;
  87669. this._yDrag.interactionsEnabled = value;
  87670. this._zDrag.interactionsEnabled = value;
  87671. };
  87672. /**
  87673. * Disposes of the gizmo
  87674. */
  87675. ScaleGizmo.prototype.dispose = function () {
  87676. this._xDrag.dispose();
  87677. this._yDrag.dispose();
  87678. this._zDrag.dispose();
  87679. };
  87680. return ScaleGizmo;
  87681. }(BABYLON.Gizmo));
  87682. BABYLON.ScaleGizmo = ScaleGizmo;
  87683. })(BABYLON || (BABYLON = {}));
  87684. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87685. var BABYLON;
  87686. (function (BABYLON) {
  87687. /**
  87688. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87689. */
  87690. var GizmoManager = /** @class */ (function () {
  87691. /**
  87692. * Instatiates a gizmo manager
  87693. * @param scene the scene to overlay the gizmos on top of
  87694. * @param options If only a single gizmo should exist at one time
  87695. */
  87696. function GizmoManager(scene, options) {
  87697. var _this = this;
  87698. this.scene = scene;
  87699. // Set of gizmos that are currently in the scene for each mesh
  87700. this._gizmoSet = {};
  87701. this._pointerObserver = null;
  87702. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87703. // Options parsing
  87704. if (!options) {
  87705. options = {};
  87706. }
  87707. if (options.singleGizmo === undefined) {
  87708. options.singleGizmo = true;
  87709. }
  87710. // Instatiate/dispose gizmos based on pointer actions
  87711. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87712. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87713. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87714. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87715. if (options.singleGizmo) {
  87716. _this._clearGizmos();
  87717. }
  87718. // Enable gizmo when mesh is selected
  87719. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87720. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87721. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87722. }
  87723. else {
  87724. if (!options.singleGizmo) {
  87725. // Disable gizmo when clicked again
  87726. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87727. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87728. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87729. }
  87730. }
  87731. }
  87732. else {
  87733. if (options.singleGizmo) {
  87734. // Disable gizmo when clicked away
  87735. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87736. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87737. if (gizmoPick && !gizmoPick.hit) {
  87738. _this._clearGizmos();
  87739. }
  87740. }
  87741. }
  87742. }
  87743. }
  87744. });
  87745. }
  87746. /**
  87747. * Disposes of the gizmo manager
  87748. */
  87749. GizmoManager.prototype.dispose = function () {
  87750. this.scene.onPointerObservable.remove(this._pointerObserver);
  87751. this._clearGizmos();
  87752. this._gizmoLayer.dispose();
  87753. };
  87754. GizmoManager.prototype._clearGizmos = function () {
  87755. for (var key in this._gizmoSet) {
  87756. if (this._gizmoSet.hasOwnProperty(key)) {
  87757. this._gizmoSet[key].positionGizmo.dispose();
  87758. this._gizmoSet[key].rotationGizmo.dispose();
  87759. delete this._gizmoSet[key];
  87760. }
  87761. }
  87762. };
  87763. return GizmoManager;
  87764. }());
  87765. BABYLON.GizmoManager = GizmoManager;
  87766. })(BABYLON || (BABYLON = {}));
  87767. //# sourceMappingURL=babylon.gizmoManager.js.map
  87768. var BABYLON;
  87769. (function (BABYLON) {
  87770. /**
  87771. * Defines a target to use with MorphTargetManager
  87772. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87773. */
  87774. var MorphTarget = /** @class */ (function () {
  87775. /**
  87776. * Creates a new MorphTarget
  87777. * @param name defines the name of the target
  87778. * @param influence defines the influence to use
  87779. */
  87780. function MorphTarget(
  87781. /** defines the name of the target */
  87782. name, influence, scene) {
  87783. if (influence === void 0) { influence = 0; }
  87784. if (scene === void 0) { scene = null; }
  87785. this.name = name;
  87786. /**
  87787. * Gets or sets the list of animations
  87788. */
  87789. this.animations = new Array();
  87790. this._positions = null;
  87791. this._normals = null;
  87792. this._tangents = null;
  87793. /**
  87794. * Observable raised when the influence changes
  87795. */
  87796. this.onInfluenceChanged = new BABYLON.Observable();
  87797. this._animationPropertiesOverride = null;
  87798. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87799. this.influence = influence;
  87800. }
  87801. Object.defineProperty(MorphTarget.prototype, "influence", {
  87802. /**
  87803. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87804. */
  87805. get: function () {
  87806. return this._influence;
  87807. },
  87808. set: function (influence) {
  87809. if (this._influence === influence) {
  87810. return;
  87811. }
  87812. var previous = this._influence;
  87813. this._influence = influence;
  87814. if (this.onInfluenceChanged.hasObservers) {
  87815. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87816. }
  87817. },
  87818. enumerable: true,
  87819. configurable: true
  87820. });
  87821. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87822. /**
  87823. * Gets or sets the animation properties override
  87824. */
  87825. get: function () {
  87826. if (!this._animationPropertiesOverride && this._scene) {
  87827. return this._scene.animationPropertiesOverride;
  87828. }
  87829. return this._animationPropertiesOverride;
  87830. },
  87831. set: function (value) {
  87832. this._animationPropertiesOverride = value;
  87833. },
  87834. enumerable: true,
  87835. configurable: true
  87836. });
  87837. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87838. /**
  87839. * Gets a boolean defining if the target contains position data
  87840. */
  87841. get: function () {
  87842. return !!this._positions;
  87843. },
  87844. enumerable: true,
  87845. configurable: true
  87846. });
  87847. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  87848. /**
  87849. * Gets a boolean defining if the target contains normal data
  87850. */
  87851. get: function () {
  87852. return !!this._normals;
  87853. },
  87854. enumerable: true,
  87855. configurable: true
  87856. });
  87857. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  87858. /**
  87859. * Gets a boolean defining if the target contains tangent data
  87860. */
  87861. get: function () {
  87862. return !!this._tangents;
  87863. },
  87864. enumerable: true,
  87865. configurable: true
  87866. });
  87867. /**
  87868. * Affects position data to this target
  87869. * @param data defines the position data to use
  87870. */
  87871. MorphTarget.prototype.setPositions = function (data) {
  87872. this._positions = data;
  87873. };
  87874. /**
  87875. * Gets the position data stored in this target
  87876. * @returns a FloatArray containing the position data (or null if not present)
  87877. */
  87878. MorphTarget.prototype.getPositions = function () {
  87879. return this._positions;
  87880. };
  87881. /**
  87882. * Affects normal data to this target
  87883. * @param data defines the normal data to use
  87884. */
  87885. MorphTarget.prototype.setNormals = function (data) {
  87886. this._normals = data;
  87887. };
  87888. /**
  87889. * Gets the normal data stored in this target
  87890. * @returns a FloatArray containing the normal data (or null if not present)
  87891. */
  87892. MorphTarget.prototype.getNormals = function () {
  87893. return this._normals;
  87894. };
  87895. /**
  87896. * Affects tangent data to this target
  87897. * @param data defines the tangent data to use
  87898. */
  87899. MorphTarget.prototype.setTangents = function (data) {
  87900. this._tangents = data;
  87901. };
  87902. /**
  87903. * Gets the tangent data stored in this target
  87904. * @returns a FloatArray containing the tangent data (or null if not present)
  87905. */
  87906. MorphTarget.prototype.getTangents = function () {
  87907. return this._tangents;
  87908. };
  87909. /**
  87910. * Serializes the current target into a Serialization object
  87911. * @returns the serialized object
  87912. */
  87913. MorphTarget.prototype.serialize = function () {
  87914. var serializationObject = {};
  87915. serializationObject.name = this.name;
  87916. serializationObject.influence = this.influence;
  87917. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  87918. if (this.hasNormals) {
  87919. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  87920. }
  87921. if (this.hasTangents) {
  87922. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  87923. }
  87924. // Animations
  87925. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  87926. return serializationObject;
  87927. };
  87928. // Statics
  87929. /**
  87930. * Creates a new target from serialized data
  87931. * @param serializationObject defines the serialized data to use
  87932. * @returns a new MorphTarget
  87933. */
  87934. MorphTarget.Parse = function (serializationObject) {
  87935. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  87936. result.setPositions(serializationObject.positions);
  87937. if (serializationObject.normals) {
  87938. result.setNormals(serializationObject.normals);
  87939. }
  87940. if (serializationObject.tangents) {
  87941. result.setTangents(serializationObject.tangents);
  87942. }
  87943. // Animations
  87944. if (serializationObject.animations) {
  87945. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  87946. var parsedAnimation = serializationObject.animations[animationIndex];
  87947. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  87948. }
  87949. }
  87950. return result;
  87951. };
  87952. /**
  87953. * Creates a MorphTarget from mesh data
  87954. * @param mesh defines the source mesh
  87955. * @param name defines the name to use for the new target
  87956. * @param influence defines the influence to attach to the target
  87957. * @returns a new MorphTarget
  87958. */
  87959. MorphTarget.FromMesh = function (mesh, name, influence) {
  87960. if (!name) {
  87961. name = mesh.name;
  87962. }
  87963. var result = new MorphTarget(name, influence, mesh.getScene());
  87964. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87966. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  87967. }
  87968. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  87969. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  87970. }
  87971. return result;
  87972. };
  87973. return MorphTarget;
  87974. }());
  87975. BABYLON.MorphTarget = MorphTarget;
  87976. })(BABYLON || (BABYLON = {}));
  87977. //# sourceMappingURL=babylon.morphTarget.js.map
  87978. var BABYLON;
  87979. (function (BABYLON) {
  87980. /**
  87981. * This class is used to deform meshes using morphing between different targets
  87982. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87983. */
  87984. var MorphTargetManager = /** @class */ (function () {
  87985. /**
  87986. * Creates a new MorphTargetManager
  87987. * @param scene defines the current scene
  87988. */
  87989. function MorphTargetManager(scene) {
  87990. if (scene === void 0) { scene = null; }
  87991. this._targets = new Array();
  87992. this._targetObservable = new Array();
  87993. this._activeTargets = new BABYLON.SmartArray(16);
  87994. this._supportsNormals = false;
  87995. this._supportsTangents = false;
  87996. this._vertexCount = 0;
  87997. this._uniqueId = 0;
  87998. this._tempInfluences = new Array();
  87999. if (!scene) {
  88000. scene = BABYLON.Engine.LastCreatedScene;
  88001. }
  88002. this._scene = scene;
  88003. if (this._scene) {
  88004. this._scene.morphTargetManagers.push(this);
  88005. this._uniqueId = this._scene.getUniqueId();
  88006. }
  88007. }
  88008. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  88009. /**
  88010. * Gets the unique ID of this manager
  88011. */
  88012. get: function () {
  88013. return this._uniqueId;
  88014. },
  88015. enumerable: true,
  88016. configurable: true
  88017. });
  88018. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  88019. /**
  88020. * Gets the number of vertices handled by this manager
  88021. */
  88022. get: function () {
  88023. return this._vertexCount;
  88024. },
  88025. enumerable: true,
  88026. configurable: true
  88027. });
  88028. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  88029. /**
  88030. * Gets a boolean indicating if this manager supports morphing of normals
  88031. */
  88032. get: function () {
  88033. return this._supportsNormals;
  88034. },
  88035. enumerable: true,
  88036. configurable: true
  88037. });
  88038. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88039. /**
  88040. * Gets a boolean indicating if this manager supports morphing of tangents
  88041. */
  88042. get: function () {
  88043. return this._supportsTangents;
  88044. },
  88045. enumerable: true,
  88046. configurable: true
  88047. });
  88048. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88049. /**
  88050. * Gets the number of targets stored in this manager
  88051. */
  88052. get: function () {
  88053. return this._targets.length;
  88054. },
  88055. enumerable: true,
  88056. configurable: true
  88057. });
  88058. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88059. /**
  88060. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88061. */
  88062. get: function () {
  88063. return this._activeTargets.length;
  88064. },
  88065. enumerable: true,
  88066. configurable: true
  88067. });
  88068. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88069. /**
  88070. * Gets the list of influences (one per target)
  88071. */
  88072. get: function () {
  88073. return this._influences;
  88074. },
  88075. enumerable: true,
  88076. configurable: true
  88077. });
  88078. /**
  88079. * Gets the active target at specified index. An active target is a target with an influence > 0
  88080. * @param index defines the index to check
  88081. * @returns the requested target
  88082. */
  88083. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88084. return this._activeTargets.data[index];
  88085. };
  88086. /**
  88087. * Gets the target at specified index
  88088. * @param index defines the index to check
  88089. * @returns the requested target
  88090. */
  88091. MorphTargetManager.prototype.getTarget = function (index) {
  88092. return this._targets[index];
  88093. };
  88094. /**
  88095. * Add a new target to this manager
  88096. * @param target defines the target to add
  88097. */
  88098. MorphTargetManager.prototype.addTarget = function (target) {
  88099. var _this = this;
  88100. this._targets.push(target);
  88101. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88102. _this._syncActiveTargets(needUpdate);
  88103. }));
  88104. this._syncActiveTargets(true);
  88105. };
  88106. /**
  88107. * Removes a target from the manager
  88108. * @param target defines the target to remove
  88109. */
  88110. MorphTargetManager.prototype.removeTarget = function (target) {
  88111. var index = this._targets.indexOf(target);
  88112. if (index >= 0) {
  88113. this._targets.splice(index, 1);
  88114. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88115. this._syncActiveTargets(true);
  88116. }
  88117. };
  88118. /**
  88119. * Serializes the current manager into a Serialization object
  88120. * @returns the serialized object
  88121. */
  88122. MorphTargetManager.prototype.serialize = function () {
  88123. var serializationObject = {};
  88124. serializationObject.id = this.uniqueId;
  88125. serializationObject.targets = [];
  88126. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88127. var target = _a[_i];
  88128. serializationObject.targets.push(target.serialize());
  88129. }
  88130. return serializationObject;
  88131. };
  88132. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88133. var influenceCount = 0;
  88134. this._activeTargets.reset();
  88135. this._supportsNormals = true;
  88136. this._supportsTangents = true;
  88137. this._vertexCount = 0;
  88138. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88139. var target = _a[_i];
  88140. this._activeTargets.push(target);
  88141. this._tempInfluences[influenceCount++] = target.influence;
  88142. var positions = target.getPositions();
  88143. if (positions) {
  88144. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88145. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88146. var vertexCount = positions.length / 3;
  88147. if (this._vertexCount === 0) {
  88148. this._vertexCount = vertexCount;
  88149. }
  88150. else if (this._vertexCount !== vertexCount) {
  88151. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88152. return;
  88153. }
  88154. }
  88155. }
  88156. if (!this._influences || this._influences.length !== influenceCount) {
  88157. this._influences = new Float32Array(influenceCount);
  88158. }
  88159. for (var index = 0; index < influenceCount; index++) {
  88160. this._influences[index] = this._tempInfluences[index];
  88161. }
  88162. if (needUpdate) {
  88163. this.synchronize();
  88164. }
  88165. };
  88166. /**
  88167. * Syncrhonize the targets with all the meshes using this morph target manager
  88168. */
  88169. MorphTargetManager.prototype.synchronize = function () {
  88170. if (!this._scene) {
  88171. return;
  88172. }
  88173. // Flag meshes as dirty to resync with the active targets
  88174. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88175. var mesh = _a[_i];
  88176. if (mesh.morphTargetManager === this) {
  88177. mesh._syncGeometryWithMorphTargetManager();
  88178. }
  88179. }
  88180. };
  88181. // Statics
  88182. /**
  88183. * Creates a new MorphTargetManager from serialized data
  88184. * @param serializationObject defines the serialized data
  88185. * @param scene defines the hosting scene
  88186. * @returns the new MorphTargetManager
  88187. */
  88188. MorphTargetManager.Parse = function (serializationObject, scene) {
  88189. var result = new MorphTargetManager(scene);
  88190. result._uniqueId = serializationObject.id;
  88191. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88192. var targetData = _a[_i];
  88193. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88194. }
  88195. return result;
  88196. };
  88197. return MorphTargetManager;
  88198. }());
  88199. BABYLON.MorphTargetManager = MorphTargetManager;
  88200. })(BABYLON || (BABYLON = {}));
  88201. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88202. var BABYLON;
  88203. (function (BABYLON) {
  88204. var Octree = /** @class */ (function () {
  88205. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88206. if (maxDepth === void 0) { maxDepth = 2; }
  88207. this.maxDepth = maxDepth;
  88208. this.dynamicContent = new Array();
  88209. this._maxBlockCapacity = maxBlockCapacity || 64;
  88210. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88211. this._creationFunc = creationFunc;
  88212. }
  88213. // Methods
  88214. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88215. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88216. };
  88217. Octree.prototype.addMesh = function (entry) {
  88218. for (var index = 0; index < this.blocks.length; index++) {
  88219. var block = this.blocks[index];
  88220. block.addEntry(entry);
  88221. }
  88222. };
  88223. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88224. this._selectionContent.reset();
  88225. for (var index = 0; index < this.blocks.length; index++) {
  88226. var block = this.blocks[index];
  88227. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88228. }
  88229. if (allowDuplicate) {
  88230. this._selectionContent.concat(this.dynamicContent);
  88231. }
  88232. else {
  88233. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88234. }
  88235. return this._selectionContent;
  88236. };
  88237. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88238. this._selectionContent.reset();
  88239. for (var index = 0; index < this.blocks.length; index++) {
  88240. var block = this.blocks[index];
  88241. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88242. }
  88243. if (allowDuplicate) {
  88244. this._selectionContent.concat(this.dynamicContent);
  88245. }
  88246. else {
  88247. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88248. }
  88249. return this._selectionContent;
  88250. };
  88251. Octree.prototype.intersectsRay = function (ray) {
  88252. this._selectionContent.reset();
  88253. for (var index = 0; index < this.blocks.length; index++) {
  88254. var block = this.blocks[index];
  88255. block.intersectsRay(ray, this._selectionContent);
  88256. }
  88257. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88258. return this._selectionContent;
  88259. };
  88260. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88261. target.blocks = new Array();
  88262. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88263. // Segmenting space
  88264. for (var x = 0; x < 2; x++) {
  88265. for (var y = 0; y < 2; y++) {
  88266. for (var z = 0; z < 2; z++) {
  88267. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88268. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88269. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88270. block.addEntries(entries);
  88271. target.blocks.push(block);
  88272. }
  88273. }
  88274. }
  88275. };
  88276. Octree.CreationFuncForMeshes = function (entry, block) {
  88277. var boundingInfo = entry.getBoundingInfo();
  88278. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88279. block.entries.push(entry);
  88280. }
  88281. };
  88282. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88283. var boundingInfo = entry.getBoundingInfo();
  88284. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88285. block.entries.push(entry);
  88286. }
  88287. };
  88288. return Octree;
  88289. }());
  88290. BABYLON.Octree = Octree;
  88291. })(BABYLON || (BABYLON = {}));
  88292. //# sourceMappingURL=babylon.octree.js.map
  88293. var BABYLON;
  88294. (function (BABYLON) {
  88295. var OctreeBlock = /** @class */ (function () {
  88296. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88297. this.entries = new Array();
  88298. this._boundingVectors = new Array();
  88299. this._capacity = capacity;
  88300. this._depth = depth;
  88301. this._maxDepth = maxDepth;
  88302. this._creationFunc = creationFunc;
  88303. this._minPoint = minPoint;
  88304. this._maxPoint = maxPoint;
  88305. this._boundingVectors.push(minPoint.clone());
  88306. this._boundingVectors.push(maxPoint.clone());
  88307. this._boundingVectors.push(minPoint.clone());
  88308. this._boundingVectors[2].x = maxPoint.x;
  88309. this._boundingVectors.push(minPoint.clone());
  88310. this._boundingVectors[3].y = maxPoint.y;
  88311. this._boundingVectors.push(minPoint.clone());
  88312. this._boundingVectors[4].z = maxPoint.z;
  88313. this._boundingVectors.push(maxPoint.clone());
  88314. this._boundingVectors[5].z = minPoint.z;
  88315. this._boundingVectors.push(maxPoint.clone());
  88316. this._boundingVectors[6].x = minPoint.x;
  88317. this._boundingVectors.push(maxPoint.clone());
  88318. this._boundingVectors[7].y = minPoint.y;
  88319. }
  88320. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88321. // Property
  88322. get: function () {
  88323. return this._capacity;
  88324. },
  88325. enumerable: true,
  88326. configurable: true
  88327. });
  88328. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88329. get: function () {
  88330. return this._minPoint;
  88331. },
  88332. enumerable: true,
  88333. configurable: true
  88334. });
  88335. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88336. get: function () {
  88337. return this._maxPoint;
  88338. },
  88339. enumerable: true,
  88340. configurable: true
  88341. });
  88342. // Methods
  88343. OctreeBlock.prototype.addEntry = function (entry) {
  88344. if (this.blocks) {
  88345. for (var index = 0; index < this.blocks.length; index++) {
  88346. var block = this.blocks[index];
  88347. block.addEntry(entry);
  88348. }
  88349. return;
  88350. }
  88351. this._creationFunc(entry, this);
  88352. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88353. this.createInnerBlocks();
  88354. }
  88355. };
  88356. OctreeBlock.prototype.addEntries = function (entries) {
  88357. for (var index = 0; index < entries.length; index++) {
  88358. var mesh = entries[index];
  88359. this.addEntry(mesh);
  88360. }
  88361. };
  88362. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88363. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88364. if (this.blocks) {
  88365. for (var index = 0; index < this.blocks.length; index++) {
  88366. var block = this.blocks[index];
  88367. block.select(frustumPlanes, selection, allowDuplicate);
  88368. }
  88369. return;
  88370. }
  88371. if (allowDuplicate) {
  88372. selection.concat(this.entries);
  88373. }
  88374. else {
  88375. selection.concatWithNoDuplicate(this.entries);
  88376. }
  88377. }
  88378. };
  88379. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88380. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88381. if (this.blocks) {
  88382. for (var index = 0; index < this.blocks.length; index++) {
  88383. var block = this.blocks[index];
  88384. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88385. }
  88386. return;
  88387. }
  88388. if (allowDuplicate) {
  88389. selection.concat(this.entries);
  88390. }
  88391. else {
  88392. selection.concatWithNoDuplicate(this.entries);
  88393. }
  88394. }
  88395. };
  88396. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88397. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88398. if (this.blocks) {
  88399. for (var index = 0; index < this.blocks.length; index++) {
  88400. var block = this.blocks[index];
  88401. block.intersectsRay(ray, selection);
  88402. }
  88403. return;
  88404. }
  88405. selection.concatWithNoDuplicate(this.entries);
  88406. }
  88407. };
  88408. OctreeBlock.prototype.createInnerBlocks = function () {
  88409. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88410. };
  88411. return OctreeBlock;
  88412. }());
  88413. BABYLON.OctreeBlock = OctreeBlock;
  88414. })(BABYLON || (BABYLON = {}));
  88415. //# sourceMappingURL=babylon.octreeBlock.js.map
  88416. var BABYLON;
  88417. (function (BABYLON) {
  88418. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88419. __extends(VRDistortionCorrectionPostProcess, _super);
  88420. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88421. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88422. 'LensCenter',
  88423. 'Scale',
  88424. 'ScaleIn',
  88425. 'HmdWarpParam'
  88426. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88427. _this._isRightEye = isRightEye;
  88428. _this._distortionFactors = vrMetrics.distortionK;
  88429. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88430. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88431. _this.adaptScaleToCurrentViewport = true;
  88432. _this.onSizeChangedObservable.add(function () {
  88433. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88434. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88435. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88436. });
  88437. _this.onApplyObservable.add(function (effect) {
  88438. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88439. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88440. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88441. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88442. });
  88443. return _this;
  88444. }
  88445. return VRDistortionCorrectionPostProcess;
  88446. }(BABYLON.PostProcess));
  88447. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88448. })(BABYLON || (BABYLON = {}));
  88449. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88450. var BABYLON;
  88451. (function (BABYLON) {
  88452. /**
  88453. * Postprocess used to generate anaglyphic rendering
  88454. */
  88455. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88456. __extends(AnaglyphPostProcess, _super);
  88457. /**
  88458. * Creates a new AnaglyphPostProcess
  88459. * @param name defines postprocess name
  88460. * @param options defines creation options or target ratio scale
  88461. * @param rigCameras defines cameras using this postprocess
  88462. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88463. * @param engine defines hosting engine
  88464. * @param reusable defines if the postprocess will be reused multiple times per frame
  88465. */
  88466. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88467. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88468. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88469. _this.onApplyObservable.add(function (effect) {
  88470. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88471. });
  88472. return _this;
  88473. }
  88474. return AnaglyphPostProcess;
  88475. }(BABYLON.PostProcess));
  88476. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88477. })(BABYLON || (BABYLON = {}));
  88478. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88479. var BABYLON;
  88480. (function (BABYLON) {
  88481. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88482. __extends(StereoscopicInterlacePostProcess, _super);
  88483. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88484. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88485. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88486. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88487. _this.onSizeChangedObservable.add(function () {
  88488. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88489. });
  88490. _this.onApplyObservable.add(function (effect) {
  88491. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88492. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88493. });
  88494. return _this;
  88495. }
  88496. return StereoscopicInterlacePostProcess;
  88497. }(BABYLON.PostProcess));
  88498. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88499. })(BABYLON || (BABYLON = {}));
  88500. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88501. var BABYLON;
  88502. (function (BABYLON) {
  88503. /**
  88504. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88505. * Screen rotation is taken into account.
  88506. */
  88507. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88508. function FreeCameraDeviceOrientationInput() {
  88509. var _this = this;
  88510. this._screenOrientationAngle = 0;
  88511. this._screenQuaternion = new BABYLON.Quaternion();
  88512. this._alpha = 0;
  88513. this._beta = 0;
  88514. this._gamma = 0;
  88515. this._orientationChanged = function () {
  88516. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88517. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88518. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88519. };
  88520. this._deviceOrientation = function (evt) {
  88521. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88522. _this._beta = evt.beta !== null ? evt.beta : 0;
  88523. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88524. };
  88525. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88526. this._orientationChanged();
  88527. }
  88528. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88529. get: function () {
  88530. return this._camera;
  88531. },
  88532. set: function (camera) {
  88533. this._camera = camera;
  88534. if (this._camera != null && !this._camera.rotationQuaternion) {
  88535. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88536. }
  88537. },
  88538. enumerable: true,
  88539. configurable: true
  88540. });
  88541. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88542. window.addEventListener("orientationchange", this._orientationChanged);
  88543. window.addEventListener("deviceorientation", this._deviceOrientation);
  88544. //In certain cases, the attach control is called AFTER orientation was changed,
  88545. //So this is needed.
  88546. this._orientationChanged();
  88547. };
  88548. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88549. window.removeEventListener("orientationchange", this._orientationChanged);
  88550. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88551. };
  88552. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88553. //if no device orientation provided, don't update the rotation.
  88554. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88555. if (!this._alpha)
  88556. return;
  88557. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88558. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88559. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88560. //Mirror on XY Plane
  88561. this._camera.rotationQuaternion.z *= -1;
  88562. this._camera.rotationQuaternion.w *= -1;
  88563. };
  88564. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88565. return "FreeCameraDeviceOrientationInput";
  88566. };
  88567. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88568. return "deviceOrientation";
  88569. };
  88570. return FreeCameraDeviceOrientationInput;
  88571. }());
  88572. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88573. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88574. })(BABYLON || (BABYLON = {}));
  88575. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88576. var BABYLON;
  88577. (function (BABYLON) {
  88578. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88579. function ArcRotateCameraVRDeviceOrientationInput() {
  88580. this.alphaCorrection = 1;
  88581. this.betaCorrection = 1;
  88582. this.gammaCorrection = 1;
  88583. this._alpha = 0;
  88584. this._gamma = 0;
  88585. this._dirty = false;
  88586. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88587. }
  88588. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88589. this.camera.attachControl(element, noPreventDefault);
  88590. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88591. };
  88592. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88593. if (evt.alpha !== null) {
  88594. this._alpha = +evt.alpha | 0;
  88595. }
  88596. if (evt.gamma !== null) {
  88597. this._gamma = +evt.gamma | 0;
  88598. }
  88599. this._dirty = true;
  88600. };
  88601. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88602. if (this._dirty) {
  88603. this._dirty = false;
  88604. if (this._gamma < 0) {
  88605. this._gamma = 180 + this._gamma;
  88606. }
  88607. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88608. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88609. }
  88610. };
  88611. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88612. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88613. };
  88614. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88615. return "ArcRotateCameraVRDeviceOrientationInput";
  88616. };
  88617. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88618. return "VRDeviceOrientation";
  88619. };
  88620. return ArcRotateCameraVRDeviceOrientationInput;
  88621. }());
  88622. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88623. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88624. })(BABYLON || (BABYLON = {}));
  88625. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88626. var BABYLON;
  88627. (function (BABYLON) {
  88628. var VRCameraMetrics = /** @class */ (function () {
  88629. function VRCameraMetrics() {
  88630. this.compensateDistortion = true;
  88631. }
  88632. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88633. get: function () {
  88634. return this.hResolution / (2 * this.vResolution);
  88635. },
  88636. enumerable: true,
  88637. configurable: true
  88638. });
  88639. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88640. get: function () {
  88641. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88642. },
  88643. enumerable: true,
  88644. configurable: true
  88645. });
  88646. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  88647. get: function () {
  88648. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88649. var h = (4 * meters) / this.hScreenSize;
  88650. return BABYLON.Matrix.Translation(h, 0, 0);
  88651. },
  88652. enumerable: true,
  88653. configurable: true
  88654. });
  88655. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  88656. get: function () {
  88657. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88658. var h = (4 * meters) / this.hScreenSize;
  88659. return BABYLON.Matrix.Translation(-h, 0, 0);
  88660. },
  88661. enumerable: true,
  88662. configurable: true
  88663. });
  88664. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  88665. get: function () {
  88666. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  88667. },
  88668. enumerable: true,
  88669. configurable: true
  88670. });
  88671. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  88672. get: function () {
  88673. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  88674. },
  88675. enumerable: true,
  88676. configurable: true
  88677. });
  88678. VRCameraMetrics.GetDefault = function () {
  88679. var result = new VRCameraMetrics();
  88680. result.hResolution = 1280;
  88681. result.vResolution = 800;
  88682. result.hScreenSize = 0.149759993;
  88683. result.vScreenSize = 0.0935999975;
  88684. result.vScreenCenter = 0.0467999987;
  88685. result.eyeToScreenDistance = 0.0410000011;
  88686. result.lensSeparationDistance = 0.0635000020;
  88687. result.interpupillaryDistance = 0.0640000030;
  88688. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88689. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88690. result.postProcessScaleFactor = 1.714605507808412;
  88691. result.lensCenterOffset = 0.151976421;
  88692. return result;
  88693. };
  88694. return VRCameraMetrics;
  88695. }());
  88696. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88697. })(BABYLON || (BABYLON = {}));
  88698. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88699. var BABYLON;
  88700. (function (BABYLON) {
  88701. /**
  88702. * This represents a WebVR camera.
  88703. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88704. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88705. */
  88706. var WebVRFreeCamera = /** @class */ (function (_super) {
  88707. __extends(WebVRFreeCamera, _super);
  88708. /**
  88709. * Instantiates a WebVRFreeCamera.
  88710. * @param name The name of the WebVRFreeCamera
  88711. * @param position The starting anchor position for the camera
  88712. * @param scene The scene the camera belongs to
  88713. * @param webVROptions a set of customizable options for the webVRCamera
  88714. */
  88715. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88716. if (webVROptions === void 0) { webVROptions = {}; }
  88717. var _this = _super.call(this, name, position, scene) || this;
  88718. _this.webVROptions = webVROptions;
  88719. /**
  88720. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88721. */
  88722. _this._vrDevice = null;
  88723. /**
  88724. * The rawPose of the vrDevice.
  88725. */
  88726. _this.rawPose = null;
  88727. _this._specsVersion = "1.1";
  88728. _this._attached = false;
  88729. _this._descendants = [];
  88730. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88731. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88732. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88733. _this._standingMatrix = null;
  88734. /**
  88735. * Represents device position in babylon space.
  88736. */
  88737. _this.devicePosition = BABYLON.Vector3.Zero();
  88738. /**
  88739. * Represents device rotation in babylon space.
  88740. */
  88741. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88742. /**
  88743. * The scale of the device to be used when translating from device space to babylon space.
  88744. */
  88745. _this.deviceScaleFactor = 1;
  88746. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88747. _this._worldToDevice = BABYLON.Matrix.Identity();
  88748. /**
  88749. * References to the webVR controllers for the vrDevice.
  88750. */
  88751. _this.controllers = [];
  88752. /**
  88753. * Emits an event when a controller is attached.
  88754. */
  88755. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88756. /**
  88757. * Emits an event when a controller's mesh has been loaded;
  88758. */
  88759. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88760. /**
  88761. * If the rig cameras be used as parent instead of this camera.
  88762. */
  88763. _this.rigParenting = true;
  88764. _this._defaultHeight = undefined;
  88765. _this._workingVector = BABYLON.Vector3.Zero();
  88766. _this._oneVector = BABYLON.Vector3.One();
  88767. _this._workingMatrix = BABYLON.Matrix.Identity();
  88768. _this._cache.position = BABYLON.Vector3.Zero();
  88769. if (webVROptions.defaultHeight) {
  88770. _this._defaultHeight = webVROptions.defaultHeight;
  88771. _this.position.y = _this._defaultHeight;
  88772. }
  88773. _this.minZ = 0.1;
  88774. //legacy support - the compensation boolean was removed.
  88775. if (arguments.length === 5) {
  88776. _this.webVROptions = arguments[4];
  88777. }
  88778. // default webVR options
  88779. if (_this.webVROptions.trackPosition == undefined) {
  88780. _this.webVROptions.trackPosition = true;
  88781. }
  88782. if (_this.webVROptions.controllerMeshes == undefined) {
  88783. _this.webVROptions.controllerMeshes = true;
  88784. }
  88785. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88786. _this.webVROptions.defaultLightingOnControllers = true;
  88787. }
  88788. _this.rotationQuaternion = new BABYLON.Quaternion();
  88789. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88790. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88791. }
  88792. //enable VR
  88793. var engine = _this.getEngine();
  88794. _this._onVREnabled = function (success) { if (success) {
  88795. _this.initControllers();
  88796. } };
  88797. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88798. engine.initWebVR().add(function (event) {
  88799. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88800. return;
  88801. }
  88802. _this._vrDevice = event.vrDisplay;
  88803. //reset the rig parameters.
  88804. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88805. if (_this._attached) {
  88806. _this.getEngine().enableVR();
  88807. }
  88808. });
  88809. if (typeof (VRFrameData) !== "undefined")
  88810. _this._frameData = new VRFrameData();
  88811. /**
  88812. * The idea behind the following lines:
  88813. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88814. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88815. * the second will not show it correctly.
  88816. *
  88817. * To solve this - each object that has the camera as parent will be added to a protected array.
  88818. * When the rig camera renders, it will take this array and set all of those to be its children.
  88819. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88820. * Amazing!
  88821. */
  88822. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88823. if (camera.parent === _this && _this.rigParenting) {
  88824. _this._descendants = _this.getDescendants(true, function (n) {
  88825. // don't take the cameras or the controllers!
  88826. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88827. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88828. return !isController && !isRigCamera;
  88829. });
  88830. _this._descendants.forEach(function (node) {
  88831. node.parent = camera;
  88832. });
  88833. }
  88834. });
  88835. scene.onAfterCameraRenderObservable.add(function (camera) {
  88836. if (camera.parent === _this && _this.rigParenting) {
  88837. _this._descendants.forEach(function (node) {
  88838. node.parent = _this;
  88839. });
  88840. }
  88841. });
  88842. return _this;
  88843. }
  88844. /**
  88845. * Gets the device distance from the ground in meters.
  88846. * @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.
  88847. */
  88848. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  88849. if (this._standingMatrix) {
  88850. // Add standing matrix offset to get real offset from ground in room
  88851. this._standingMatrix.getTranslationToRef(this._workingVector);
  88852. return this._deviceRoomPosition.y + this._workingVector.y;
  88853. }
  88854. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  88855. return this._defaultHeight || 0;
  88856. };
  88857. /**
  88858. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88859. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  88860. */
  88861. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  88862. var _this = this;
  88863. if (callback === void 0) { callback = function (bool) { }; }
  88864. // Use standing matrix if available
  88865. this.getEngine().initWebVRAsync().then(function (result) {
  88866. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  88867. callback(false);
  88868. }
  88869. else {
  88870. _this._standingMatrix = new BABYLON.Matrix();
  88871. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  88872. if (!_this.getScene().useRightHandedSystem) {
  88873. [2, 6, 8, 9, 14].forEach(function (num) {
  88874. if (_this._standingMatrix) {
  88875. _this._standingMatrix.m[num] *= -1;
  88876. }
  88877. });
  88878. }
  88879. callback(true);
  88880. }
  88881. });
  88882. };
  88883. /**
  88884. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88885. * @returns A promise with a boolean set to if the standing matrix is supported.
  88886. */
  88887. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  88888. var _this = this;
  88889. return new Promise(function (res, rej) {
  88890. _this.useStandingMatrix(function (supported) {
  88891. res(supported);
  88892. });
  88893. });
  88894. };
  88895. /**
  88896. * Disposes the camera
  88897. */
  88898. WebVRFreeCamera.prototype.dispose = function () {
  88899. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  88900. _super.prototype.dispose.call(this);
  88901. };
  88902. /**
  88903. * Gets a vrController by name.
  88904. * @param name The name of the controller to retreive
  88905. * @returns the controller matching the name specified or null if not found
  88906. */
  88907. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  88908. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  88909. var gp = _a[_i];
  88910. if (gp.hand === name) {
  88911. return gp;
  88912. }
  88913. }
  88914. return null;
  88915. };
  88916. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  88917. /**
  88918. * The controller corrisponding to the users left hand.
  88919. */
  88920. get: function () {
  88921. if (!this._leftController) {
  88922. this._leftController = this.getControllerByName("left");
  88923. }
  88924. return this._leftController;
  88925. },
  88926. enumerable: true,
  88927. configurable: true
  88928. });
  88929. ;
  88930. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  88931. /**
  88932. * The controller corrisponding to the users right hand.
  88933. */
  88934. get: function () {
  88935. if (!this._rightController) {
  88936. this._rightController = this.getControllerByName("right");
  88937. }
  88938. return this._rightController;
  88939. },
  88940. enumerable: true,
  88941. configurable: true
  88942. });
  88943. ;
  88944. /**
  88945. * Casts a ray forward from the vrCamera's gaze.
  88946. * @param length Length of the ray (default: 100)
  88947. * @returns the ray corrisponding to the gaze
  88948. */
  88949. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  88950. if (length === void 0) { length = 100; }
  88951. if (this.leftCamera) {
  88952. // Use left eye to avoid computation to compute center on every call
  88953. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  88954. }
  88955. else {
  88956. return _super.prototype.getForwardRay.call(this, length);
  88957. }
  88958. };
  88959. /**
  88960. * Updates the camera based on device's frame data
  88961. */
  88962. WebVRFreeCamera.prototype._checkInputs = function () {
  88963. if (this._vrDevice && this._vrDevice.isPresenting) {
  88964. this._vrDevice.getFrameData(this._frameData);
  88965. this.updateFromDevice(this._frameData.pose);
  88966. }
  88967. _super.prototype._checkInputs.call(this);
  88968. };
  88969. /**
  88970. * Updates the poseControlled values based on the input device pose.
  88971. * @param poseData Pose coming from the device
  88972. */
  88973. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  88974. if (poseData && poseData.orientation) {
  88975. this.rawPose = poseData;
  88976. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  88977. if (this.getScene().useRightHandedSystem) {
  88978. this._deviceRoomRotationQuaternion.z *= -1;
  88979. this._deviceRoomRotationQuaternion.w *= -1;
  88980. }
  88981. if (this.webVROptions.trackPosition && this.rawPose.position) {
  88982. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  88983. if (this.getScene().useRightHandedSystem) {
  88984. this._deviceRoomPosition.z *= -1;
  88985. }
  88986. }
  88987. }
  88988. };
  88989. /**
  88990. * WebVR's attach control will start broadcasting frames to the device.
  88991. * Note that in certain browsers (chrome for example) this function must be called
  88992. * within a user-interaction callback. Example:
  88993. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  88994. *
  88995. * @param element html element to attach the vrDevice to
  88996. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  88997. */
  88998. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  88999. _super.prototype.attachControl.call(this, element, noPreventDefault);
  89000. this._attached = true;
  89001. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  89002. if (this._vrDevice) {
  89003. this.getEngine().enableVR();
  89004. }
  89005. };
  89006. /**
  89007. * Detaches the camera from the html element and disables VR
  89008. *
  89009. * @param element html element to detach from
  89010. */
  89011. WebVRFreeCamera.prototype.detachControl = function (element) {
  89012. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  89013. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  89014. _super.prototype.detachControl.call(this, element);
  89015. this._attached = false;
  89016. this.getEngine().disableVR();
  89017. };
  89018. /**
  89019. * @returns the name of this class
  89020. */
  89021. WebVRFreeCamera.prototype.getClassName = function () {
  89022. return "WebVRFreeCamera";
  89023. };
  89024. /**
  89025. * Calls resetPose on the vrDisplay
  89026. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  89027. */
  89028. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  89029. //uses the vrDisplay's "resetPose()".
  89030. //pitch and roll won't be affected.
  89031. this._vrDevice.resetPose();
  89032. };
  89033. /**
  89034. * Updates the rig cameras (left and right eye)
  89035. */
  89036. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89037. var camLeft = this._rigCameras[0];
  89038. var camRight = this._rigCameras[1];
  89039. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89040. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89041. camLeft.position.copyFrom(this._deviceRoomPosition);
  89042. camRight.position.copyFrom(this._deviceRoomPosition);
  89043. };
  89044. /**
  89045. * Updates the cached values of the camera
  89046. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89047. */
  89048. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89049. var _this = this;
  89050. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89051. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89052. if (!this.updateCacheCalled) {
  89053. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89054. this.updateCacheCalled = true;
  89055. this.update();
  89056. }
  89057. // Set working vector to the device position in room space rotated by the new rotation
  89058. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89059. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89060. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89061. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89062. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89063. // Add translation from anchor position
  89064. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89065. this._workingVector.addInPlace(this.position);
  89066. this._workingVector.subtractInPlace(this._cache.position);
  89067. this._deviceToWorld.setTranslation(this._workingVector);
  89068. // Set an inverted matrix to be used when updating the camera
  89069. this._deviceToWorld.invertToRef(this._worldToDevice);
  89070. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89071. this.controllers.forEach(function (controller) {
  89072. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89073. controller.update();
  89074. });
  89075. }
  89076. if (!ignoreParentClass) {
  89077. _super.prototype._updateCache.call(this);
  89078. }
  89079. this.updateCacheCalled = false;
  89080. };
  89081. /**
  89082. * Updates the current device position and rotation in the babylon world
  89083. */
  89084. WebVRFreeCamera.prototype.update = function () {
  89085. // Get current device position in babylon world
  89086. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89087. // Get current device rotation in babylon world
  89088. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89089. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89090. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89091. _super.prototype.update.call(this);
  89092. };
  89093. /**
  89094. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89095. * @returns an identity matrix
  89096. */
  89097. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89098. return BABYLON.Matrix.Identity();
  89099. };
  89100. /**
  89101. * This function is called by the two RIG cameras.
  89102. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89103. */
  89104. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89105. var _this = this;
  89106. // Update the parent camera prior to using a child camera to avoid desynchronization
  89107. var parentCamera = this._cameraRigParams["parentCamera"];
  89108. parentCamera._updateCache();
  89109. //WebVR 1.1
  89110. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89111. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89112. if (!this.getScene().useRightHandedSystem) {
  89113. [2, 6, 8, 9, 14].forEach(function (num) {
  89114. _this._webvrViewMatrix.m[num] *= -1;
  89115. });
  89116. }
  89117. // update the camera rotation matrix
  89118. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89119. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89120. // Computing target and final matrix
  89121. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89122. // should the view matrix be updated with scale and position offset?
  89123. if (parentCamera.deviceScaleFactor !== 1) {
  89124. this._webvrViewMatrix.invert();
  89125. // scale the position, if set
  89126. if (parentCamera.deviceScaleFactor) {
  89127. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89128. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89129. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89130. }
  89131. this._webvrViewMatrix.invert();
  89132. }
  89133. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89134. // Compute global position
  89135. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89136. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89137. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89138. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89139. this._markSyncedWithParent();
  89140. return this._webvrViewMatrix;
  89141. };
  89142. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89143. var _this = this;
  89144. var parentCamera = this.parent;
  89145. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89146. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89147. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89148. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89149. //babylon compatible matrix
  89150. if (!this.getScene().useRightHandedSystem) {
  89151. [8, 9, 10, 11].forEach(function (num) {
  89152. _this._projectionMatrix.m[num] *= -1;
  89153. });
  89154. }
  89155. return this._projectionMatrix;
  89156. };
  89157. /**
  89158. * Initializes the controllers and their meshes
  89159. */
  89160. WebVRFreeCamera.prototype.initControllers = function () {
  89161. var _this = this;
  89162. this.controllers = [];
  89163. var manager = this.getScene().gamepadManager;
  89164. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89165. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89166. var webVrController = gamepad;
  89167. if (webVrController.defaultModel) {
  89168. webVrController.defaultModel.setEnabled(false);
  89169. }
  89170. if (webVrController.hand === "right") {
  89171. _this._rightController = null;
  89172. }
  89173. if (webVrController.hand === "left") {
  89174. _this._leftController = null;
  89175. }
  89176. var controllerIndex = _this.controllers.indexOf(webVrController);
  89177. if (controllerIndex !== -1) {
  89178. _this.controllers.splice(controllerIndex, 1);
  89179. }
  89180. }
  89181. });
  89182. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89183. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89184. var webVrController_1 = gamepad;
  89185. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89186. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89187. if (_this.webVROptions.controllerMeshes) {
  89188. if (webVrController_1.defaultModel) {
  89189. webVrController_1.defaultModel.setEnabled(true);
  89190. }
  89191. else {
  89192. // Load the meshes
  89193. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89194. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89195. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89196. if (_this.webVROptions.defaultLightingOnControllers) {
  89197. if (!_this._lightOnControllers) {
  89198. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89199. }
  89200. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89201. var children = mesh.getChildren();
  89202. if (children.length !== 0) {
  89203. children.forEach(function (mesh) {
  89204. light.includedOnlyMeshes.push(mesh);
  89205. activateLightOnSubMeshes_1(mesh, light);
  89206. });
  89207. }
  89208. };
  89209. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89210. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89211. }
  89212. });
  89213. }
  89214. }
  89215. webVrController_1.attachToPoseControlledCamera(_this);
  89216. // since this is async - sanity check. Is the controller already stored?
  89217. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89218. //add to the controllers array
  89219. _this.controllers.push(webVrController_1);
  89220. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89221. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89222. // So we're overriding setting left & right manually to be sure
  89223. var firstViveWandDetected = false;
  89224. for (var i = 0; i < _this.controllers.length; i++) {
  89225. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89226. if (!firstViveWandDetected) {
  89227. firstViveWandDetected = true;
  89228. _this.controllers[i].hand = "left";
  89229. }
  89230. else {
  89231. _this.controllers[i].hand = "right";
  89232. }
  89233. }
  89234. }
  89235. //did we find enough controllers? Great! let the developer know.
  89236. if (_this.controllers.length >= 2) {
  89237. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89238. }
  89239. }
  89240. }
  89241. });
  89242. };
  89243. return WebVRFreeCamera;
  89244. }(BABYLON.FreeCamera));
  89245. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89246. })(BABYLON || (BABYLON = {}));
  89247. //# sourceMappingURL=babylon.webVRCamera.js.map
  89248. var BABYLON;
  89249. (function (BABYLON) {
  89250. // We're mainly based on the logic defined into the FreeCamera code
  89251. /**
  89252. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89253. * being tilted forward or back and left or right.
  89254. */
  89255. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89256. __extends(DeviceOrientationCamera, _super);
  89257. /**
  89258. * Creates a new device orientation camera
  89259. * @param name The name of the camera
  89260. * @param position The start position camera
  89261. * @param scene The scene the camera belongs to
  89262. */
  89263. function DeviceOrientationCamera(name, position, scene) {
  89264. var _this = _super.call(this, name, position, scene) || this;
  89265. _this._quaternionCache = new BABYLON.Quaternion();
  89266. _this.inputs.addDeviceOrientation();
  89267. return _this;
  89268. }
  89269. /**
  89270. * Gets the current instance class name ("DeviceOrientationCamera").
  89271. * This helps avoiding instanceof at run time.
  89272. * @returns the class name
  89273. */
  89274. DeviceOrientationCamera.prototype.getClassName = function () {
  89275. return "DeviceOrientationCamera";
  89276. };
  89277. /**
  89278. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89279. */
  89280. DeviceOrientationCamera.prototype._checkInputs = function () {
  89281. _super.prototype._checkInputs.call(this);
  89282. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89283. if (this._initialQuaternion) {
  89284. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89285. }
  89286. };
  89287. /**
  89288. * Reset the camera to its default orientation on the specified axis only.
  89289. * @param axis The axis to reset
  89290. */
  89291. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89292. var _this = this;
  89293. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89294. //can only work if this camera has a rotation quaternion already.
  89295. if (!this.rotationQuaternion)
  89296. return;
  89297. if (!this._initialQuaternion) {
  89298. this._initialQuaternion = new BABYLON.Quaternion();
  89299. }
  89300. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89301. ['x', 'y', 'z'].forEach(function (axisName) {
  89302. if (!axis[axisName]) {
  89303. _this._initialQuaternion[axisName] = 0;
  89304. }
  89305. else {
  89306. _this._initialQuaternion[axisName] *= -1;
  89307. }
  89308. });
  89309. this._initialQuaternion.normalize();
  89310. //force rotation update
  89311. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89312. };
  89313. return DeviceOrientationCamera;
  89314. }(BABYLON.FreeCamera));
  89315. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89316. })(BABYLON || (BABYLON = {}));
  89317. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89318. var BABYLON;
  89319. (function (BABYLON) {
  89320. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89321. __extends(VRDeviceOrientationFreeCamera, _super);
  89322. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89323. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89324. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89325. var _this = _super.call(this, name, position, scene) || this;
  89326. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89327. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89328. return _this;
  89329. }
  89330. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89331. return "VRDeviceOrientationFreeCamera";
  89332. };
  89333. return VRDeviceOrientationFreeCamera;
  89334. }(BABYLON.DeviceOrientationCamera));
  89335. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89336. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89337. __extends(VRDeviceOrientationGamepadCamera, _super);
  89338. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89339. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89340. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89341. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89342. _this.inputs.addGamepad();
  89343. return _this;
  89344. }
  89345. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89346. return "VRDeviceOrientationGamepadCamera";
  89347. };
  89348. return VRDeviceOrientationGamepadCamera;
  89349. }(VRDeviceOrientationFreeCamera));
  89350. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89351. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89352. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89353. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89354. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89355. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89356. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89357. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89358. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89359. _this.inputs.addVRDeviceOrientation();
  89360. return _this;
  89361. }
  89362. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89363. return "VRDeviceOrientationArcRotateCamera";
  89364. };
  89365. return VRDeviceOrientationArcRotateCamera;
  89366. }(BABYLON.ArcRotateCamera));
  89367. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89368. })(BABYLON || (BABYLON = {}));
  89369. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89370. var BABYLON;
  89371. (function (BABYLON) {
  89372. /**
  89373. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89374. */
  89375. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89376. __extends(AnaglyphFreeCamera, _super);
  89377. /**
  89378. * Creates a new AnaglyphFreeCamera
  89379. * @param name defines camera name
  89380. * @param position defines initial position
  89381. * @param interaxialDistance defines distance between each color axis
  89382. * @param scene defines the hosting scene
  89383. */
  89384. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89385. var _this = _super.call(this, name, position, scene) || this;
  89386. _this.interaxialDistance = interaxialDistance;
  89387. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89388. return _this;
  89389. }
  89390. /**
  89391. * Gets camera class name
  89392. * @returns AnaglyphFreeCamera
  89393. */
  89394. AnaglyphFreeCamera.prototype.getClassName = function () {
  89395. return "AnaglyphFreeCamera";
  89396. };
  89397. return AnaglyphFreeCamera;
  89398. }(BABYLON.FreeCamera));
  89399. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89400. /**
  89401. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89402. */
  89403. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89404. __extends(AnaglyphArcRotateCamera, _super);
  89405. /**
  89406. * Creates a new AnaglyphArcRotateCamera
  89407. * @param name defines camera name
  89408. * @param alpha defines alpha angle (in radians)
  89409. * @param beta defines beta angle (in radians)
  89410. * @param radius defines radius
  89411. * @param target defines camera target
  89412. * @param interaxialDistance defines distance between each color axis
  89413. * @param scene defines the hosting scene
  89414. */
  89415. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89416. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89417. _this.interaxialDistance = interaxialDistance;
  89418. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89419. return _this;
  89420. }
  89421. /**
  89422. * Gets camera class name
  89423. * @returns AnaglyphArcRotateCamera
  89424. */
  89425. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89426. return "AnaglyphArcRotateCamera";
  89427. };
  89428. return AnaglyphArcRotateCamera;
  89429. }(BABYLON.ArcRotateCamera));
  89430. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89431. /**
  89432. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89433. */
  89434. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89435. __extends(AnaglyphGamepadCamera, _super);
  89436. /**
  89437. * Creates a new AnaglyphGamepadCamera
  89438. * @param name defines camera name
  89439. * @param position defines initial position
  89440. * @param interaxialDistance defines distance between each color axis
  89441. * @param scene defines the hosting scene
  89442. */
  89443. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89444. var _this = _super.call(this, name, position, scene) || this;
  89445. _this.interaxialDistance = interaxialDistance;
  89446. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89447. return _this;
  89448. }
  89449. /**
  89450. * Gets camera class name
  89451. * @returns AnaglyphGamepadCamera
  89452. */
  89453. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89454. return "AnaglyphGamepadCamera";
  89455. };
  89456. return AnaglyphGamepadCamera;
  89457. }(BABYLON.GamepadCamera));
  89458. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89459. /**
  89460. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89461. */
  89462. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89463. __extends(AnaglyphUniversalCamera, _super);
  89464. /**
  89465. * Creates a new AnaglyphUniversalCamera
  89466. * @param name defines camera name
  89467. * @param position defines initial position
  89468. * @param interaxialDistance defines distance between each color axis
  89469. * @param scene defines the hosting scene
  89470. */
  89471. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89472. var _this = _super.call(this, name, position, scene) || this;
  89473. _this.interaxialDistance = interaxialDistance;
  89474. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89475. return _this;
  89476. }
  89477. /**
  89478. * Gets camera class name
  89479. * @returns AnaglyphUniversalCamera
  89480. */
  89481. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89482. return "AnaglyphUniversalCamera";
  89483. };
  89484. return AnaglyphUniversalCamera;
  89485. }(BABYLON.UniversalCamera));
  89486. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89487. /**
  89488. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89489. */
  89490. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89491. __extends(StereoscopicFreeCamera, _super);
  89492. /**
  89493. * Creates a new StereoscopicFreeCamera
  89494. * @param name defines camera name
  89495. * @param position defines initial position
  89496. * @param interaxialDistance defines distance between each color axis
  89497. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89498. * @param scene defines the hosting scene
  89499. */
  89500. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89501. var _this = _super.call(this, name, position, scene) || this;
  89502. _this.interaxialDistance = interaxialDistance;
  89503. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89504. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89505. return _this;
  89506. }
  89507. /**
  89508. * Gets camera class name
  89509. * @returns StereoscopicFreeCamera
  89510. */
  89511. StereoscopicFreeCamera.prototype.getClassName = function () {
  89512. return "StereoscopicFreeCamera";
  89513. };
  89514. return StereoscopicFreeCamera;
  89515. }(BABYLON.FreeCamera));
  89516. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89517. /**
  89518. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89519. */
  89520. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89521. __extends(StereoscopicArcRotateCamera, _super);
  89522. /**
  89523. * Creates a new StereoscopicArcRotateCamera
  89524. * @param name defines camera name
  89525. * @param alpha defines alpha angle (in radians)
  89526. * @param beta defines beta angle (in radians)
  89527. * @param radius defines radius
  89528. * @param target defines camera target
  89529. * @param interaxialDistance defines distance between each color axis
  89530. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89531. * @param scene defines the hosting scene
  89532. */
  89533. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89534. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89535. _this.interaxialDistance = interaxialDistance;
  89536. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89537. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89538. return _this;
  89539. }
  89540. /**
  89541. * Gets camera class name
  89542. * @returns StereoscopicArcRotateCamera
  89543. */
  89544. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89545. return "StereoscopicArcRotateCamera";
  89546. };
  89547. return StereoscopicArcRotateCamera;
  89548. }(BABYLON.ArcRotateCamera));
  89549. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89550. /**
  89551. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89552. */
  89553. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89554. __extends(StereoscopicGamepadCamera, _super);
  89555. /**
  89556. * Creates a new StereoscopicGamepadCamera
  89557. * @param name defines camera name
  89558. * @param position defines initial position
  89559. * @param interaxialDistance defines distance between each color axis
  89560. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89561. * @param scene defines the hosting scene
  89562. */
  89563. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89564. var _this = _super.call(this, name, position, scene) || this;
  89565. _this.interaxialDistance = interaxialDistance;
  89566. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89567. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89568. return _this;
  89569. }
  89570. /**
  89571. * Gets camera class name
  89572. * @returns StereoscopicGamepadCamera
  89573. */
  89574. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89575. return "StereoscopicGamepadCamera";
  89576. };
  89577. return StereoscopicGamepadCamera;
  89578. }(BABYLON.GamepadCamera));
  89579. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89580. /**
  89581. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89582. */
  89583. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89584. __extends(StereoscopicUniversalCamera, _super);
  89585. /**
  89586. * Creates a new StereoscopicUniversalCamera
  89587. * @param name defines camera name
  89588. * @param position defines initial position
  89589. * @param interaxialDistance defines distance between each color axis
  89590. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89591. * @param scene defines the hosting scene
  89592. */
  89593. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89594. var _this = _super.call(this, name, position, scene) || this;
  89595. _this.interaxialDistance = interaxialDistance;
  89596. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89597. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89598. return _this;
  89599. }
  89600. /**
  89601. * Gets camera class name
  89602. * @returns StereoscopicUniversalCamera
  89603. */
  89604. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89605. return "StereoscopicUniversalCamera";
  89606. };
  89607. return StereoscopicUniversalCamera;
  89608. }(BABYLON.UniversalCamera));
  89609. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89610. })(BABYLON || (BABYLON = {}));
  89611. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89612. var BABYLON;
  89613. (function (BABYLON) {
  89614. var VRExperienceHelperGazer = /** @class */ (function () {
  89615. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89616. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89617. this.scene = scene;
  89618. this._pointerDownOnMeshAsked = false;
  89619. this._isActionableMesh = false;
  89620. this._teleportationRequestInitiated = false;
  89621. this._teleportationBackRequestInitiated = false;
  89622. this._rotationRightAsked = false;
  89623. this._rotationLeftAsked = false;
  89624. this._dpadPressed = true;
  89625. this._activePointer = false;
  89626. this._id = VRExperienceHelperGazer._idCounter++;
  89627. // Gaze tracker
  89628. if (!gazeTrackerToClone) {
  89629. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89630. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89631. this._gazeTracker.isPickable = false;
  89632. this._gazeTracker.isVisible = false;
  89633. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89634. targetMat.specularColor = BABYLON.Color3.Black();
  89635. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89636. targetMat.backFaceCulling = false;
  89637. this._gazeTracker.material = targetMat;
  89638. }
  89639. else {
  89640. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89641. }
  89642. }
  89643. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89644. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89645. };
  89646. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  89647. this._pointerDownOnMeshAsked = true;
  89648. if (this._currentHit) {
  89649. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  89650. }
  89651. };
  89652. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  89653. if (this._currentHit) {
  89654. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  89655. }
  89656. this._pointerDownOnMeshAsked = false;
  89657. };
  89658. VRExperienceHelperGazer.prototype._activatePointer = function () {
  89659. this._activePointer = true;
  89660. };
  89661. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  89662. this._activePointer = false;
  89663. };
  89664. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  89665. if (distance === void 0) { distance = 100; }
  89666. };
  89667. VRExperienceHelperGazer.prototype.dispose = function () {
  89668. this._interactionsEnabled = false;
  89669. this._teleportationEnabled = false;
  89670. if (this._gazeTracker) {
  89671. this._gazeTracker.dispose();
  89672. }
  89673. };
  89674. VRExperienceHelperGazer._idCounter = 0;
  89675. return VRExperienceHelperGazer;
  89676. }());
  89677. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89678. __extends(VRExperienceHelperControllerGazer, _super);
  89679. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89680. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89681. _this.webVRController = webVRController;
  89682. // Laser pointer
  89683. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89684. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89685. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89686. laserPointerMaterial.alpha = 0.6;
  89687. _this._laserPointer.material = laserPointerMaterial;
  89688. _this._laserPointer.rotation.x = Math.PI / 2;
  89689. _this._laserPointer.position.z = -0.5;
  89690. _this._laserPointer.isVisible = false;
  89691. if (!webVRController.mesh) {
  89692. // Create an empty mesh that is used prior to loading the high quality model
  89693. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89694. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89695. preloadPointerPose.rotation.x = -0.7;
  89696. preloadMesh.addChild(preloadPointerPose);
  89697. webVRController.attachToMesh(preloadMesh);
  89698. }
  89699. _this._setLaserPointerParent(webVRController.mesh);
  89700. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89701. _this._setLaserPointerParent(mesh);
  89702. });
  89703. return _this;
  89704. }
  89705. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89706. return this.webVRController.getForwardRay(length);
  89707. };
  89708. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89709. _super.prototype._activatePointer.call(this);
  89710. this._laserPointer.isVisible = true;
  89711. };
  89712. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89713. _super.prototype._deactivatePointer.call(this);
  89714. this._laserPointer.isVisible = false;
  89715. };
  89716. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89717. this._laserPointer.material.emissiveColor = color;
  89718. };
  89719. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89720. var makeNotPick = function (root) {
  89721. root.name += " laserPointer";
  89722. root.getChildMeshes().forEach(function (c) {
  89723. makeNotPick(c);
  89724. });
  89725. };
  89726. makeNotPick(mesh);
  89727. var childMeshes = mesh.getChildMeshes();
  89728. this.webVRController._pointingPoseNode = null;
  89729. for (var i = 0; i < childMeshes.length; i++) {
  89730. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89731. mesh = childMeshes[i];
  89732. this.webVRController._pointingPoseNode = mesh;
  89733. break;
  89734. }
  89735. }
  89736. this._laserPointer.parent = mesh;
  89737. };
  89738. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89739. if (distance === void 0) { distance = 100; }
  89740. this._laserPointer.scaling.y = distance;
  89741. this._laserPointer.position.z = -distance / 2;
  89742. };
  89743. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89744. _super.prototype.dispose.call(this);
  89745. this._laserPointer.dispose();
  89746. if (this._meshAttachedObserver) {
  89747. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89748. }
  89749. };
  89750. return VRExperienceHelperControllerGazer;
  89751. }(VRExperienceHelperGazer));
  89752. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89753. __extends(VRExperienceHelperCameraGazer, _super);
  89754. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89755. var _this = _super.call(this, scene) || this;
  89756. _this.getCamera = getCamera;
  89757. return _this;
  89758. }
  89759. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89760. var camera = this.getCamera();
  89761. if (camera) {
  89762. return camera.getForwardRay(length);
  89763. }
  89764. else {
  89765. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89766. }
  89767. };
  89768. return VRExperienceHelperCameraGazer;
  89769. }(VRExperienceHelperGazer));
  89770. /**
  89771. * Helps to quickly add VR support to an existing scene.
  89772. * See http://doc.babylonjs.com/how_to/webvr_helper
  89773. */
  89774. var VRExperienceHelper = /** @class */ (function () {
  89775. /**
  89776. * Instantiates a VRExperienceHelper.
  89777. * Helps to quickly add VR support to an existing scene.
  89778. * @param scene The scene the VRExperienceHelper belongs to.
  89779. * @param webVROptions Options to modify the vr experience helper's behavior.
  89780. */
  89781. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89782. if (webVROptions === void 0) { webVROptions = {}; }
  89783. var _this = this;
  89784. this.webVROptions = webVROptions;
  89785. // Can the system support WebVR, even if a headset isn't plugged in?
  89786. this._webVRsupported = false;
  89787. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89788. this._webVRready = false;
  89789. // Are we waiting for the requestPresent callback to complete?
  89790. this._webVRrequesting = false;
  89791. // Are we presenting to the headset right now?
  89792. this._webVRpresenting = false;
  89793. // Are we presenting in the fullscreen fallback?
  89794. this._fullscreenVRpresenting = false;
  89795. /**
  89796. * Observable raised when entering VR.
  89797. */
  89798. this.onEnteringVRObservable = new BABYLON.Observable();
  89799. /**
  89800. * Observable raised when exiting VR.
  89801. */
  89802. this.onExitingVRObservable = new BABYLON.Observable();
  89803. /**
  89804. * Observable raised when controller mesh is loaded.
  89805. */
  89806. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89807. this._useCustomVRButton = false;
  89808. this._teleportationRequested = false;
  89809. this._teleportActive = false;
  89810. this._floorMeshesCollection = [];
  89811. this._rotationAllowed = true;
  89812. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89813. this._isDefaultTeleportationTarget = true;
  89814. this._teleportationFillColor = "#444444";
  89815. this._teleportationBorderColor = "#FFFFFF";
  89816. this._rotationAngle = 0;
  89817. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89818. this._padSensibilityUp = 0.65;
  89819. this._padSensibilityDown = 0.35;
  89820. this.leftController = null;
  89821. this.rightController = null;
  89822. /**
  89823. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89824. */
  89825. this.onNewMeshSelected = new BABYLON.Observable();
  89826. /**
  89827. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89828. */
  89829. this.onNewMeshPicked = new BABYLON.Observable();
  89830. /**
  89831. * Observable raised before camera teleportation
  89832. */
  89833. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89834. /**
  89835. * Observable raised after camera teleportation
  89836. */
  89837. this.onAfterCameraTeleport = new BABYLON.Observable();
  89838. /**
  89839. * Observable raised when current selected mesh gets unselected
  89840. */
  89841. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89842. /**
  89843. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  89844. */
  89845. this.teleportationEnabled = true;
  89846. this._teleportationInitialized = false;
  89847. this._interactionsEnabled = false;
  89848. this._interactionsRequested = false;
  89849. this._displayGaze = true;
  89850. this._displayLaserPointer = true;
  89851. this._onResize = function () {
  89852. _this.moveButtonToBottomRight();
  89853. if (_this._fullscreenVRpresenting && _this._webVRready) {
  89854. _this.exitVR();
  89855. }
  89856. };
  89857. this._onFullscreenChange = function () {
  89858. if (document.fullscreen !== undefined) {
  89859. _this._fullscreenVRpresenting = document.fullscreen;
  89860. }
  89861. else if (document.mozFullScreen !== undefined) {
  89862. _this._fullscreenVRpresenting = document.mozFullScreen;
  89863. }
  89864. else if (document.webkitIsFullScreen !== undefined) {
  89865. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  89866. }
  89867. else if (document.msIsFullScreen !== undefined) {
  89868. _this._fullscreenVRpresenting = document.msIsFullScreen;
  89869. }
  89870. if (!_this._fullscreenVRpresenting && _this._canvas) {
  89871. _this.exitVR();
  89872. if (!_this._useCustomVRButton) {
  89873. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  89874. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  89875. }
  89876. }
  89877. };
  89878. this.beforeRender = function () {
  89879. if (_this.leftController && _this.leftController._activePointer) {
  89880. _this._castRayAndSelectObject(_this.leftController);
  89881. }
  89882. if (_this.rightController && _this.rightController._activePointer) {
  89883. _this._castRayAndSelectObject(_this.rightController);
  89884. }
  89885. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  89886. _this._castRayAndSelectObject(_this._cameraGazer);
  89887. }
  89888. else {
  89889. _this._cameraGazer._gazeTracker.isVisible = false;
  89890. }
  89891. };
  89892. this._onNewGamepadConnected = function (gamepad) {
  89893. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  89894. if (gamepad.leftStick) {
  89895. gamepad.onleftstickchanged(function (stickValues) {
  89896. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  89897. // Listening to classic/xbox gamepad only if no VR controller is active
  89898. if ((!_this.leftController && !_this.rightController) ||
  89899. ((_this.leftController && !_this.leftController._activePointer) &&
  89900. (_this.rightController && !_this.rightController._activePointer))) {
  89901. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  89902. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  89903. }
  89904. }
  89905. });
  89906. }
  89907. if (gamepad.rightStick) {
  89908. gamepad.onrightstickchanged(function (stickValues) {
  89909. if (_this._teleportationInitialized) {
  89910. _this._checkRotate(stickValues, _this._cameraGazer);
  89911. }
  89912. });
  89913. }
  89914. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  89915. gamepad.onbuttondown(function (buttonPressed) {
  89916. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89917. _this._cameraGazer._selectionPointerDown();
  89918. }
  89919. });
  89920. gamepad.onbuttonup(function (buttonPressed) {
  89921. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89922. _this._cameraGazer._selectionPointerUp();
  89923. }
  89924. });
  89925. }
  89926. }
  89927. else {
  89928. var webVRController = gamepad;
  89929. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  89930. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  89931. _this.rightController = controller;
  89932. }
  89933. else {
  89934. _this.leftController = controller;
  89935. }
  89936. _this._tryEnableInteractionOnController(controller);
  89937. }
  89938. };
  89939. // 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
  89940. this._tryEnableInteractionOnController = function (controller) {
  89941. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  89942. _this._enableInteractionOnController(controller);
  89943. }
  89944. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  89945. _this._enableTeleportationOnController(controller);
  89946. }
  89947. };
  89948. this._onNewGamepadDisconnected = function (gamepad) {
  89949. if (gamepad instanceof BABYLON.WebVRController) {
  89950. if (gamepad.hand === "left" && _this.leftController != null) {
  89951. _this.leftController.dispose();
  89952. _this.leftController = null;
  89953. }
  89954. if (gamepad.hand === "right" && _this.rightController != null) {
  89955. _this.rightController.dispose();
  89956. _this.rightController = null;
  89957. }
  89958. }
  89959. };
  89960. this._workingVector = BABYLON.Vector3.Zero();
  89961. this._workingQuaternion = BABYLON.Quaternion.Identity();
  89962. this._workingMatrix = BABYLON.Matrix.Identity();
  89963. this._scene = scene;
  89964. this._canvas = scene.getEngine().getRenderingCanvas();
  89965. // Parse options
  89966. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  89967. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  89968. }
  89969. if (webVROptions.createDeviceOrientationCamera === undefined) {
  89970. webVROptions.createDeviceOrientationCamera = true;
  89971. }
  89972. if (webVROptions.laserToggle === undefined) {
  89973. webVROptions.laserToggle = true;
  89974. }
  89975. if (webVROptions.defaultHeight === undefined) {
  89976. webVROptions.defaultHeight = 1.7;
  89977. }
  89978. if (webVROptions.useCustomVRButton) {
  89979. this._useCustomVRButton = true;
  89980. if (webVROptions.customVRButton) {
  89981. this._btnVR = webVROptions.customVRButton;
  89982. }
  89983. }
  89984. if (webVROptions.rayLength) {
  89985. this._rayLength = webVROptions.rayLength;
  89986. }
  89987. this._defaultHeight = webVROptions.defaultHeight;
  89988. if (webVROptions.positionScale) {
  89989. this._rayLength *= webVROptions.positionScale;
  89990. this._defaultHeight *= webVROptions.positionScale;
  89991. }
  89992. // Set position
  89993. if (this._scene.activeCamera) {
  89994. this._position = this._scene.activeCamera.position.clone();
  89995. }
  89996. else {
  89997. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  89998. }
  89999. // Set non-vr camera
  90000. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  90001. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  90002. // Copy data from existing camera
  90003. if (this._scene.activeCamera) {
  90004. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90005. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  90006. // Set rotation from previous camera
  90007. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  90008. var targetCamera = this._scene.activeCamera;
  90009. if (targetCamera.rotationQuaternion) {
  90010. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  90011. }
  90012. else {
  90013. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  90014. }
  90015. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  90016. }
  90017. }
  90018. this._scene.activeCamera = this._deviceOrientationCamera;
  90019. if (this._canvas) {
  90020. this._scene.activeCamera.attachControl(this._canvas);
  90021. }
  90022. }
  90023. else {
  90024. this._existingCamera = this._scene.activeCamera;
  90025. }
  90026. // Create VR cameras
  90027. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90028. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  90029. }
  90030. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  90031. this._webVRCamera.useStandingMatrix();
  90032. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  90033. // Create default button
  90034. if (!this._useCustomVRButton) {
  90035. this._btnVR = document.createElement("BUTTON");
  90036. this._btnVR.className = "babylonVRicon";
  90037. this._btnVR.id = "babylonVRiconbtn";
  90038. this._btnVR.title = "Click to switch to VR";
  90039. 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) }";
  90040. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90041. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90042. // css += ".babylonVRicon.vrdisplaysupported { }";
  90043. // css += ".babylonVRicon.vrdisplayready { }";
  90044. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90045. var style = document.createElement('style');
  90046. style.appendChild(document.createTextNode(css));
  90047. document.getElementsByTagName('head')[0].appendChild(style);
  90048. this.moveButtonToBottomRight();
  90049. }
  90050. // VR button click event
  90051. if (this._btnVR) {
  90052. this._btnVR.addEventListener("click", function () {
  90053. if (!_this.isInVRMode) {
  90054. _this.enterVR();
  90055. }
  90056. else {
  90057. _this.exitVR();
  90058. }
  90059. });
  90060. }
  90061. // Window events
  90062. window.addEventListener("resize", this._onResize);
  90063. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90064. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90065. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90066. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90067. // Display vr button when headset is connected
  90068. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90069. this.displayVRButton();
  90070. }
  90071. else {
  90072. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90073. if (e.vrDisplay) {
  90074. _this.displayVRButton();
  90075. }
  90076. });
  90077. }
  90078. // Exiting VR mode using 'ESC' key on desktop
  90079. this._onKeyDown = function (event) {
  90080. if (event.keyCode === 27 && _this.isInVRMode) {
  90081. _this.exitVR();
  90082. }
  90083. };
  90084. document.addEventListener("keydown", this._onKeyDown);
  90085. // Exiting VR mode double tapping the touch screen
  90086. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90087. if (_this.isInVRMode) {
  90088. _this.exitVR();
  90089. if (_this._fullscreenVRpresenting) {
  90090. _this._scene.getEngine().switchFullscreen(true);
  90091. }
  90092. }
  90093. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90094. // Listen for WebVR display changes
  90095. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90096. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90097. this._onVRRequestPresentStart = function () {
  90098. _this._webVRrequesting = true;
  90099. _this.updateButtonVisibility();
  90100. };
  90101. this._onVRRequestPresentComplete = function (success) {
  90102. _this._webVRrequesting = false;
  90103. _this.updateButtonVisibility();
  90104. };
  90105. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90106. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90107. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90108. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90109. scene.onDisposeObservable.add(function () {
  90110. _this.dispose();
  90111. });
  90112. // Gamepad connection events
  90113. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90114. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90115. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90116. this.updateButtonVisibility();
  90117. //create easing functions
  90118. this._circleEase = new BABYLON.CircleEase();
  90119. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90120. if (this.webVROptions.floorMeshes) {
  90121. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90122. }
  90123. }
  90124. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90125. /** Return this.onEnteringVRObservable
  90126. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90127. */
  90128. get: function () {
  90129. return this.onEnteringVRObservable;
  90130. },
  90131. enumerable: true,
  90132. configurable: true
  90133. });
  90134. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90135. /** Return this.onExitingVRObservable
  90136. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90137. */
  90138. get: function () {
  90139. return this.onExitingVRObservable;
  90140. },
  90141. enumerable: true,
  90142. configurable: true
  90143. });
  90144. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90145. /** Return this.onControllerMeshLoadedObservable
  90146. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90147. */
  90148. get: function () {
  90149. return this.onControllerMeshLoadedObservable;
  90150. },
  90151. enumerable: true,
  90152. configurable: true
  90153. });
  90154. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90155. /**
  90156. * The mesh used to display where the user is going to teleport.
  90157. */
  90158. get: function () {
  90159. return this._teleportationTarget;
  90160. },
  90161. /**
  90162. * Sets the mesh to be used to display where the user is going to teleport.
  90163. */
  90164. set: function (value) {
  90165. if (value) {
  90166. value.name = "teleportationTarget";
  90167. this._isDefaultTeleportationTarget = false;
  90168. this._teleportationTarget = value;
  90169. }
  90170. },
  90171. enumerable: true,
  90172. configurable: true
  90173. });
  90174. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90175. /**
  90176. * The mesh used to display where the user is selecting,
  90177. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90178. * See http://doc.babylonjs.com/resources/baking_transformations
  90179. */
  90180. get: function () {
  90181. return this._cameraGazer._gazeTracker;
  90182. },
  90183. set: function (value) {
  90184. if (value) {
  90185. this._cameraGazer._gazeTracker = value;
  90186. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90187. this._cameraGazer._gazeTracker.isPickable = false;
  90188. this._cameraGazer._gazeTracker.isVisible = false;
  90189. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90190. if (this.leftController) {
  90191. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90192. }
  90193. if (this.rightController) {
  90194. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90195. }
  90196. }
  90197. },
  90198. enumerable: true,
  90199. configurable: true
  90200. });
  90201. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90202. /**
  90203. * If the ray of the gaze should be displayed.
  90204. */
  90205. get: function () {
  90206. return this._displayGaze;
  90207. },
  90208. /**
  90209. * Sets if the ray of the gaze should be displayed.
  90210. */
  90211. set: function (value) {
  90212. this._displayGaze = value;
  90213. if (!value) {
  90214. this._cameraGazer._gazeTracker.isVisible = false;
  90215. if (this.leftController) {
  90216. this.leftController._gazeTracker.isVisible = false;
  90217. }
  90218. if (this.rightController) {
  90219. this.rightController._gazeTracker.isVisible = false;
  90220. }
  90221. }
  90222. },
  90223. enumerable: true,
  90224. configurable: true
  90225. });
  90226. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90227. /**
  90228. * If the ray of the LaserPointer should be displayed.
  90229. */
  90230. get: function () {
  90231. return this._displayLaserPointer;
  90232. },
  90233. /**
  90234. * Sets if the ray of the LaserPointer should be displayed.
  90235. */
  90236. set: function (value) {
  90237. this._displayLaserPointer = value;
  90238. if (!value) {
  90239. if (this.rightController) {
  90240. this.rightController._deactivatePointer();
  90241. this.rightController._gazeTracker.isVisible = false;
  90242. }
  90243. if (this.leftController) {
  90244. this.leftController._deactivatePointer();
  90245. this.leftController._gazeTracker.isVisible = false;
  90246. }
  90247. }
  90248. else {
  90249. if (this.rightController) {
  90250. this.rightController._activatePointer();
  90251. }
  90252. if (this.leftController) {
  90253. this.leftController._activatePointer();
  90254. }
  90255. }
  90256. },
  90257. enumerable: true,
  90258. configurable: true
  90259. });
  90260. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90261. /**
  90262. * The deviceOrientationCamera used as the camera when not in VR.
  90263. */
  90264. get: function () {
  90265. return this._deviceOrientationCamera;
  90266. },
  90267. enumerable: true,
  90268. configurable: true
  90269. });
  90270. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90271. /**
  90272. * Based on the current WebVR support, returns the current VR camera used.
  90273. */
  90274. get: function () {
  90275. if (this._webVRready) {
  90276. return this._webVRCamera;
  90277. }
  90278. else {
  90279. return this._scene.activeCamera;
  90280. }
  90281. },
  90282. enumerable: true,
  90283. configurable: true
  90284. });
  90285. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90286. /**
  90287. * The webVRCamera which is used when in VR.
  90288. */
  90289. get: function () {
  90290. return this._webVRCamera;
  90291. },
  90292. enumerable: true,
  90293. configurable: true
  90294. });
  90295. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90296. /**
  90297. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90298. */
  90299. get: function () {
  90300. return this._vrDeviceOrientationCamera;
  90301. },
  90302. enumerable: true,
  90303. configurable: true
  90304. });
  90305. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90306. get: function () {
  90307. var result = this._cameraGazer._teleportationRequestInitiated
  90308. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90309. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90310. return result;
  90311. },
  90312. enumerable: true,
  90313. configurable: true
  90314. });
  90315. // Raised when one of the controller has loaded successfully its associated default mesh
  90316. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90317. if (this.leftController && this.leftController.webVRController == webVRController) {
  90318. if (webVRController.mesh) {
  90319. this.leftController._setLaserPointerParent(webVRController.mesh);
  90320. }
  90321. }
  90322. if (this.rightController && this.rightController.webVRController == webVRController) {
  90323. if (webVRController.mesh) {
  90324. this.rightController._setLaserPointerParent(webVRController.mesh);
  90325. }
  90326. }
  90327. try {
  90328. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90329. }
  90330. catch (err) {
  90331. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90332. }
  90333. };
  90334. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90335. /**
  90336. * Gets a value indicating if we are currently in VR mode.
  90337. */
  90338. get: function () {
  90339. return this._webVRpresenting || this._fullscreenVRpresenting;
  90340. },
  90341. enumerable: true,
  90342. configurable: true
  90343. });
  90344. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90345. var vrDisplay = this._scene.getEngine().getVRDevice();
  90346. if (vrDisplay) {
  90347. var wasPresenting = this._webVRpresenting;
  90348. // A VR display is connected
  90349. this._webVRpresenting = vrDisplay.isPresenting;
  90350. if (wasPresenting && !this._webVRpresenting)
  90351. this.exitVR();
  90352. }
  90353. else {
  90354. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90355. }
  90356. this.updateButtonVisibility();
  90357. };
  90358. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90359. this._webVRsupported = eventArgs.vrSupported;
  90360. this._webVRready = !!eventArgs.vrDisplay;
  90361. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90362. this.updateButtonVisibility();
  90363. };
  90364. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90365. if (this._canvas && !this._useCustomVRButton) {
  90366. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90367. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90368. }
  90369. };
  90370. VRExperienceHelper.prototype.displayVRButton = function () {
  90371. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90372. document.body.appendChild(this._btnVR);
  90373. this._btnVRDisplayed = true;
  90374. }
  90375. };
  90376. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90377. if (!this._btnVR || this._useCustomVRButton) {
  90378. return;
  90379. }
  90380. this._btnVR.className = "babylonVRicon";
  90381. if (this.isInVRMode) {
  90382. this._btnVR.className += " vrdisplaypresenting";
  90383. }
  90384. else {
  90385. if (this._webVRready)
  90386. this._btnVR.className += " vrdisplayready";
  90387. if (this._webVRsupported)
  90388. this._btnVR.className += " vrdisplaysupported";
  90389. if (this._webVRrequesting)
  90390. this._btnVR.className += " vrdisplayrequesting";
  90391. }
  90392. };
  90393. /**
  90394. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90395. * Otherwise, will use the fullscreen API.
  90396. */
  90397. VRExperienceHelper.prototype.enterVR = function () {
  90398. if (this.onEnteringVRObservable) {
  90399. try {
  90400. this.onEnteringVRObservable.notifyObservers(this);
  90401. }
  90402. catch (err) {
  90403. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90404. }
  90405. }
  90406. if (this._scene.activeCamera) {
  90407. this._position = this._scene.activeCamera.position.clone();
  90408. // make sure that we return to the last active camera
  90409. this._existingCamera = this._scene.activeCamera;
  90410. }
  90411. if (this._webVRrequesting)
  90412. return;
  90413. // If WebVR is supported and a headset is connected
  90414. if (this._webVRready) {
  90415. if (!this._webVRpresenting) {
  90416. this._webVRCamera.position = this._position;
  90417. this._scene.activeCamera = this._webVRCamera;
  90418. }
  90419. }
  90420. else if (this._vrDeviceOrientationCamera) {
  90421. this._vrDeviceOrientationCamera.position = this._position;
  90422. if (this._scene.activeCamera) {
  90423. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90424. }
  90425. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90426. this._scene.getEngine().switchFullscreen(true);
  90427. this.updateButtonVisibility();
  90428. }
  90429. if (this._scene.activeCamera && this._canvas) {
  90430. this._scene.activeCamera.attachControl(this._canvas);
  90431. }
  90432. if (this._interactionsEnabled) {
  90433. this._scene.registerBeforeRender(this.beforeRender);
  90434. }
  90435. };
  90436. /**
  90437. * Attempt to exit VR, or fullscreen.
  90438. */
  90439. VRExperienceHelper.prototype.exitVR = function () {
  90440. if (this.onExitingVRObservable) {
  90441. try {
  90442. this.onExitingVRObservable.notifyObservers(this);
  90443. }
  90444. catch (err) {
  90445. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90446. }
  90447. }
  90448. if (this._webVRpresenting) {
  90449. this._scene.getEngine().disableVR();
  90450. }
  90451. if (this._scene.activeCamera) {
  90452. this._position = this._scene.activeCamera.position.clone();
  90453. }
  90454. if (this._deviceOrientationCamera) {
  90455. this._deviceOrientationCamera.position = this._position;
  90456. this._scene.activeCamera = this._deviceOrientationCamera;
  90457. if (this._canvas) {
  90458. this._scene.activeCamera.attachControl(this._canvas);
  90459. }
  90460. }
  90461. else if (this._existingCamera) {
  90462. this._existingCamera.position = this._position;
  90463. this._scene.activeCamera = this._existingCamera;
  90464. }
  90465. this.updateButtonVisibility();
  90466. if (this._interactionsEnabled) {
  90467. this._scene.unregisterBeforeRender(this.beforeRender);
  90468. }
  90469. // resize to update width and height when exiting vr exits fullscreen
  90470. this._scene.getEngine().resize();
  90471. };
  90472. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90473. /**
  90474. * The position of the vr experience helper.
  90475. */
  90476. get: function () {
  90477. return this._position;
  90478. },
  90479. /**
  90480. * Sets the position of the vr experience helper.
  90481. */
  90482. set: function (value) {
  90483. this._position = value;
  90484. if (this._scene.activeCamera) {
  90485. this._scene.activeCamera.position = value;
  90486. }
  90487. },
  90488. enumerable: true,
  90489. configurable: true
  90490. });
  90491. /**
  90492. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90493. */
  90494. VRExperienceHelper.prototype.enableInteractions = function () {
  90495. var _this = this;
  90496. if (!this._interactionsEnabled) {
  90497. this._interactionsRequested = true;
  90498. if (this.leftController) {
  90499. this._enableInteractionOnController(this.leftController);
  90500. }
  90501. if (this.rightController) {
  90502. this._enableInteractionOnController(this.rightController);
  90503. }
  90504. this.raySelectionPredicate = function (mesh) {
  90505. return mesh.isVisible;
  90506. };
  90507. this.meshSelectionPredicate = function (mesh) {
  90508. return true;
  90509. };
  90510. this._raySelectionPredicate = function (mesh) {
  90511. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90512. && mesh.name.indexOf("teleportationTarget") === -1
  90513. && mesh.name.indexOf("torusTeleportation") === -1
  90514. && mesh.name.indexOf("laserPointer") === -1)) {
  90515. return _this.raySelectionPredicate(mesh);
  90516. }
  90517. return false;
  90518. };
  90519. this._interactionsEnabled = true;
  90520. }
  90521. };
  90522. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90523. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90524. if (this._floorMeshesCollection[i].id === mesh.id) {
  90525. return true;
  90526. }
  90527. }
  90528. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90529. return true;
  90530. }
  90531. return false;
  90532. };
  90533. /**
  90534. * Adds a floor mesh to be used for teleportation.
  90535. * @param floorMesh the mesh to be used for teleportation.
  90536. */
  90537. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90538. if (!this._floorMeshesCollection) {
  90539. return;
  90540. }
  90541. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90542. return;
  90543. }
  90544. this._floorMeshesCollection.push(floorMesh);
  90545. };
  90546. /**
  90547. * Removes a floor mesh from being used for teleportation.
  90548. * @param floorMesh the mesh to be removed.
  90549. */
  90550. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90551. if (!this._floorMeshesCollection) {
  90552. return;
  90553. }
  90554. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90555. if (meshIndex !== -1) {
  90556. this._floorMeshesCollection.splice(meshIndex, 1);
  90557. }
  90558. };
  90559. /**
  90560. * Enables interactions and teleportation using the VR controllers and gaze.
  90561. * @param vrTeleportationOptions options to modify teleportation behavior.
  90562. */
  90563. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90564. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90565. if (!this._teleportationInitialized) {
  90566. this._teleportationRequested = true;
  90567. this.enableInteractions();
  90568. if (vrTeleportationOptions.floorMeshName) {
  90569. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90570. }
  90571. if (vrTeleportationOptions.floorMeshes) {
  90572. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90573. }
  90574. if (this.leftController != null) {
  90575. this._enableTeleportationOnController(this.leftController);
  90576. }
  90577. if (this.rightController != null) {
  90578. this._enableTeleportationOnController(this.rightController);
  90579. }
  90580. // Creates an image processing post process for the vignette not relying
  90581. // on the main scene configuration for image processing to reduce setup and spaces
  90582. // (gamma/linear) conflicts.
  90583. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90584. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90585. imageProcessingConfiguration.vignetteEnabled = true;
  90586. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90587. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90588. this._teleportationInitialized = true;
  90589. if (this._isDefaultTeleportationTarget) {
  90590. this._createTeleportationCircles();
  90591. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90592. }
  90593. }
  90594. };
  90595. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90596. var _this = this;
  90597. var controllerMesh = controller.webVRController.mesh;
  90598. if (controllerMesh) {
  90599. controller._interactionsEnabled = true;
  90600. controller._activatePointer();
  90601. if (this.webVROptions.laserToggle) {
  90602. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90603. // Enabling / disabling laserPointer
  90604. if (_this._displayLaserPointer && stateObject.value === 1) {
  90605. if (controller._activePointer) {
  90606. controller._deactivatePointer();
  90607. }
  90608. else {
  90609. controller._activatePointer();
  90610. }
  90611. if (_this.displayGaze) {
  90612. controller._gazeTracker.isVisible = controller._activePointer;
  90613. }
  90614. }
  90615. });
  90616. }
  90617. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90618. if (!controller._pointerDownOnMeshAsked) {
  90619. if (stateObject.value > _this._padSensibilityUp) {
  90620. controller._selectionPointerDown();
  90621. }
  90622. }
  90623. else if (stateObject.value < _this._padSensibilityDown) {
  90624. controller._selectionPointerUp();
  90625. }
  90626. });
  90627. }
  90628. };
  90629. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90630. // Dont teleport if another gaze already requested teleportation
  90631. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90632. return;
  90633. }
  90634. if (!gazer._teleportationRequestInitiated) {
  90635. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90636. gazer._activatePointer();
  90637. gazer._teleportationRequestInitiated = true;
  90638. }
  90639. }
  90640. else {
  90641. // Listening to the proper controller values changes to confirm teleportation
  90642. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90643. if (this._teleportActive) {
  90644. this._teleportCamera(this._haloCenter);
  90645. }
  90646. gazer._teleportationRequestInitiated = false;
  90647. }
  90648. }
  90649. };
  90650. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  90651. // Only rotate when user is not currently selecting a teleportation location
  90652. if (gazer._teleportationRequestInitiated) {
  90653. return;
  90654. }
  90655. if (!gazer._rotationLeftAsked) {
  90656. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  90657. gazer._rotationLeftAsked = true;
  90658. if (this._rotationAllowed) {
  90659. this._rotateCamera(false);
  90660. }
  90661. }
  90662. }
  90663. else {
  90664. if (stateObject.x > -this._padSensibilityDown) {
  90665. gazer._rotationLeftAsked = false;
  90666. }
  90667. }
  90668. if (!gazer._rotationRightAsked) {
  90669. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  90670. gazer._rotationRightAsked = true;
  90671. if (this._rotationAllowed) {
  90672. this._rotateCamera(true);
  90673. }
  90674. }
  90675. }
  90676. else {
  90677. if (stateObject.x < this._padSensibilityDown) {
  90678. gazer._rotationRightAsked = false;
  90679. }
  90680. }
  90681. };
  90682. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90683. // Only teleport backwards when user is not currently selecting a teleportation location
  90684. if (gazer._teleportationRequestInitiated) {
  90685. return;
  90686. }
  90687. // Teleport backwards
  90688. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90689. if (!gazer._teleportationBackRequestInitiated) {
  90690. if (!this.currentVRCamera) {
  90691. return;
  90692. }
  90693. // Get rotation and position of the current camera
  90694. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90695. var position = this.currentVRCamera.position;
  90696. // If the camera has device position, use that instead
  90697. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90698. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90699. position = this.currentVRCamera.devicePosition;
  90700. }
  90701. // Get matrix with only the y rotation of the device rotation
  90702. rotation.toEulerAnglesToRef(this._workingVector);
  90703. this._workingVector.z = 0;
  90704. this._workingVector.x = 0;
  90705. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90706. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90707. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90708. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90709. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90710. var ray = new BABYLON.Ray(position, this._workingVector);
  90711. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90712. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90713. this._teleportCamera(hit.pickedPoint);
  90714. }
  90715. gazer._teleportationBackRequestInitiated = true;
  90716. }
  90717. }
  90718. else {
  90719. gazer._teleportationBackRequestInitiated = false;
  90720. }
  90721. };
  90722. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90723. var _this = this;
  90724. var controllerMesh = controller.webVRController.mesh;
  90725. if (controllerMesh) {
  90726. if (!controller._interactionsEnabled) {
  90727. this._enableInteractionOnController(controller);
  90728. }
  90729. controller._interactionsEnabled = true;
  90730. controller._teleportationEnabled = true;
  90731. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90732. controller._dpadPressed = false;
  90733. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90734. controller._dpadPressed = stateObject.pressed;
  90735. if (!controller._dpadPressed) {
  90736. controller._rotationLeftAsked = false;
  90737. controller._rotationRightAsked = false;
  90738. controller._teleportationBackRequestInitiated = false;
  90739. }
  90740. });
  90741. }
  90742. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90743. if (_this.teleportationEnabled) {
  90744. _this._checkTeleportBackwards(stateObject, controller);
  90745. _this._checkTeleportWithRay(stateObject, controller);
  90746. }
  90747. _this._checkRotate(stateObject, controller);
  90748. });
  90749. }
  90750. };
  90751. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90752. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90753. this._teleportationTarget.isPickable = false;
  90754. var length = 512;
  90755. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90756. dynamicTexture.hasAlpha = true;
  90757. var context = dynamicTexture.getContext();
  90758. var centerX = length / 2;
  90759. var centerY = length / 2;
  90760. var radius = 200;
  90761. context.beginPath();
  90762. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90763. context.fillStyle = this._teleportationFillColor;
  90764. context.fill();
  90765. context.lineWidth = 10;
  90766. context.strokeStyle = this._teleportationBorderColor;
  90767. context.stroke();
  90768. context.closePath();
  90769. dynamicTexture.update();
  90770. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90771. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90772. this._teleportationTarget.material = teleportationCircleMaterial;
  90773. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90774. torus.isPickable = false;
  90775. torus.parent = this._teleportationTarget;
  90776. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90777. var keys = [];
  90778. keys.push({
  90779. frame: 0,
  90780. value: 0
  90781. });
  90782. keys.push({
  90783. frame: 30,
  90784. value: 0.4
  90785. });
  90786. keys.push({
  90787. frame: 60,
  90788. value: 0
  90789. });
  90790. animationInnerCircle.setKeys(keys);
  90791. var easingFunction = new BABYLON.SineEase();
  90792. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90793. animationInnerCircle.setEasingFunction(easingFunction);
  90794. torus.animations = [];
  90795. torus.animations.push(animationInnerCircle);
  90796. this._scene.beginAnimation(torus, 0, 60, true);
  90797. this._hideTeleportationTarget();
  90798. };
  90799. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90800. this._teleportActive = true;
  90801. if (this._teleportationInitialized) {
  90802. this._teleportationTarget.isVisible = true;
  90803. if (this._isDefaultTeleportationTarget) {
  90804. this._teleportationTarget.getChildren()[0].isVisible = true;
  90805. }
  90806. }
  90807. };
  90808. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90809. this._teleportActive = false;
  90810. if (this._teleportationInitialized) {
  90811. this._teleportationTarget.isVisible = false;
  90812. if (this._isDefaultTeleportationTarget) {
  90813. this._teleportationTarget.getChildren()[0].isVisible = false;
  90814. }
  90815. }
  90816. };
  90817. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90818. var _this = this;
  90819. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90820. return;
  90821. }
  90822. if (right) {
  90823. this._rotationAngle++;
  90824. }
  90825. else {
  90826. this._rotationAngle--;
  90827. }
  90828. this.currentVRCamera.animations = [];
  90829. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90830. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90831. var animationRotationKeys = [];
  90832. animationRotationKeys.push({
  90833. frame: 0,
  90834. value: this.currentVRCamera.rotationQuaternion
  90835. });
  90836. animationRotationKeys.push({
  90837. frame: 6,
  90838. value: target
  90839. });
  90840. animationRotation.setKeys(animationRotationKeys);
  90841. animationRotation.setEasingFunction(this._circleEase);
  90842. this.currentVRCamera.animations.push(animationRotation);
  90843. this._postProcessMove.animations = [];
  90844. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90845. var vignetteWeightKeys = [];
  90846. vignetteWeightKeys.push({
  90847. frame: 0,
  90848. value: 0
  90849. });
  90850. vignetteWeightKeys.push({
  90851. frame: 3,
  90852. value: 4
  90853. });
  90854. vignetteWeightKeys.push({
  90855. frame: 6,
  90856. value: 0
  90857. });
  90858. animationPP.setKeys(vignetteWeightKeys);
  90859. animationPP.setEasingFunction(this._circleEase);
  90860. this._postProcessMove.animations.push(animationPP);
  90861. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90862. var vignetteStretchKeys = [];
  90863. vignetteStretchKeys.push({
  90864. frame: 0,
  90865. value: 0
  90866. });
  90867. vignetteStretchKeys.push({
  90868. frame: 3,
  90869. value: 10
  90870. });
  90871. vignetteStretchKeys.push({
  90872. frame: 6,
  90873. value: 0
  90874. });
  90875. animationPP2.setKeys(vignetteStretchKeys);
  90876. animationPP2.setEasingFunction(this._circleEase);
  90877. this._postProcessMove.animations.push(animationPP2);
  90878. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90879. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90880. this._postProcessMove.samples = 4;
  90881. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90882. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  90883. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90884. });
  90885. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  90886. };
  90887. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  90888. if (hit.pickedPoint) {
  90889. if (gazer._teleportationRequestInitiated) {
  90890. this._displayTeleportationTarget();
  90891. this._haloCenter.copyFrom(hit.pickedPoint);
  90892. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  90893. }
  90894. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  90895. if (pickNormal) {
  90896. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90897. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90898. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  90899. }
  90900. this._teleportationTarget.position.y += 0.1;
  90901. }
  90902. };
  90903. VRExperienceHelper.prototype._teleportCamera = function (location) {
  90904. var _this = this;
  90905. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90906. return;
  90907. }
  90908. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  90909. // offset of the headset from the anchor.
  90910. if (this.webVRCamera.leftCamera) {
  90911. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  90912. this._workingVector.subtractInPlace(this.webVRCamera.position);
  90913. location.subtractToRef(this._workingVector, this._workingVector);
  90914. }
  90915. else {
  90916. this._workingVector.copyFrom(location);
  90917. }
  90918. // Add height to account for user's height offset
  90919. if (this.isInVRMode) {
  90920. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  90921. }
  90922. else {
  90923. this._workingVector.y += this._defaultHeight;
  90924. }
  90925. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  90926. // Create animation from the camera's position to the new location
  90927. this.currentVRCamera.animations = [];
  90928. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90929. var animationCameraTeleportationKeys = [{
  90930. frame: 0,
  90931. value: this.currentVRCamera.position
  90932. },
  90933. {
  90934. frame: 11,
  90935. value: this._workingVector
  90936. }
  90937. ];
  90938. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  90939. animationCameraTeleportation.setEasingFunction(this._circleEase);
  90940. this.currentVRCamera.animations.push(animationCameraTeleportation);
  90941. this._postProcessMove.animations = [];
  90942. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90943. var vignetteWeightKeys = [];
  90944. vignetteWeightKeys.push({
  90945. frame: 0,
  90946. value: 0
  90947. });
  90948. vignetteWeightKeys.push({
  90949. frame: 5,
  90950. value: 8
  90951. });
  90952. vignetteWeightKeys.push({
  90953. frame: 11,
  90954. value: 0
  90955. });
  90956. animationPP.setKeys(vignetteWeightKeys);
  90957. this._postProcessMove.animations.push(animationPP);
  90958. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90959. var vignetteStretchKeys = [];
  90960. vignetteStretchKeys.push({
  90961. frame: 0,
  90962. value: 0
  90963. });
  90964. vignetteStretchKeys.push({
  90965. frame: 5,
  90966. value: 10
  90967. });
  90968. vignetteStretchKeys.push({
  90969. frame: 11,
  90970. value: 0
  90971. });
  90972. animationPP2.setKeys(vignetteStretchKeys);
  90973. this._postProcessMove.animations.push(animationPP2);
  90974. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90975. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90976. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90977. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  90978. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90979. });
  90980. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  90981. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  90982. });
  90983. this._hideTeleportationTarget();
  90984. };
  90985. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  90986. if (normal) {
  90987. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  90988. if (angle < Math.PI / 2) {
  90989. normal.scaleInPlace(-1);
  90990. }
  90991. }
  90992. return normal;
  90993. };
  90994. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  90995. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90996. return;
  90997. }
  90998. var ray = gazer._getForwardRay(this._rayLength);
  90999. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  91000. if (hit) {
  91001. // Populate the contrllers mesh that can be used for drag/drop
  91002. if (gazer._laserPointer) {
  91003. hit.originMesh = gazer._laserPointer.parent;
  91004. }
  91005. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  91006. }
  91007. gazer._currentHit = hit;
  91008. // Moving the gazeTracker on the mesh face targetted
  91009. if (hit && hit.pickedPoint) {
  91010. if (this._displayGaze) {
  91011. var multiplier = 1;
  91012. gazer._gazeTracker.isVisible = true;
  91013. if (gazer._isActionableMesh) {
  91014. multiplier = 3;
  91015. }
  91016. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  91017. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  91018. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  91019. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  91020. // To avoid z-fighting
  91021. var deltaFighting = 0.002;
  91022. if (pickNormal) {
  91023. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  91024. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  91025. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  91026. }
  91027. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  91028. if (gazer._gazeTracker.position.x < 0) {
  91029. gazer._gazeTracker.position.x += deltaFighting;
  91030. }
  91031. else {
  91032. gazer._gazeTracker.position.x -= deltaFighting;
  91033. }
  91034. if (gazer._gazeTracker.position.y < 0) {
  91035. gazer._gazeTracker.position.y += deltaFighting;
  91036. }
  91037. else {
  91038. gazer._gazeTracker.position.y -= deltaFighting;
  91039. }
  91040. if (gazer._gazeTracker.position.z < 0) {
  91041. gazer._gazeTracker.position.z += deltaFighting;
  91042. }
  91043. else {
  91044. gazer._gazeTracker.position.z -= deltaFighting;
  91045. }
  91046. }
  91047. // Changing the size of the laser pointer based on the distance from the targetted point
  91048. gazer._updatePointerDistance(hit.distance);
  91049. }
  91050. else {
  91051. gazer._updatePointerDistance();
  91052. gazer._gazeTracker.isVisible = false;
  91053. }
  91054. if (hit && hit.pickedMesh) {
  91055. // The object selected is the floor, we're in a teleportation scenario
  91056. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91057. // Moving the teleportation area to this targetted point
  91058. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91059. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91060. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91061. }
  91062. gazer._currentMeshSelected = null;
  91063. if (gazer._teleportationRequestInitiated) {
  91064. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91065. }
  91066. return;
  91067. }
  91068. // If not, we're in a selection scenario
  91069. //this._teleportationAllowed = false;
  91070. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91071. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91072. this.onNewMeshPicked.notifyObservers(hit);
  91073. gazer._currentMeshSelected = hit.pickedMesh;
  91074. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91075. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91076. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91077. gazer._isActionableMesh = true;
  91078. }
  91079. else {
  91080. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91081. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91082. gazer._isActionableMesh = false;
  91083. }
  91084. try {
  91085. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91086. }
  91087. catch (err) {
  91088. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91089. }
  91090. }
  91091. else {
  91092. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91093. gazer._currentMeshSelected = null;
  91094. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91095. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91096. }
  91097. }
  91098. }
  91099. else {
  91100. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91101. gazer._currentMeshSelected = null;
  91102. //this._teleportationAllowed = false;
  91103. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91104. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91105. }
  91106. };
  91107. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91108. if (mesh) {
  91109. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91110. }
  91111. };
  91112. /**
  91113. * Sets the color of the laser ray from the vr controllers.
  91114. * @param color new color for the ray.
  91115. */
  91116. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91117. if (this.leftController) {
  91118. this.leftController._setLaserPointerColor(color);
  91119. }
  91120. if (this.rightController) {
  91121. this.rightController._setLaserPointerColor(color);
  91122. }
  91123. };
  91124. /**
  91125. * Sets the color of the ray from the vr headsets gaze.
  91126. * @param color new color for the ray.
  91127. */
  91128. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91129. if (!this._cameraGazer._gazeTracker.material) {
  91130. return;
  91131. }
  91132. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91133. if (this.leftController) {
  91134. this.leftController._gazeTracker.material.emissiveColor = color;
  91135. }
  91136. if (this.rightController) {
  91137. this.rightController._gazeTracker.material.emissiveColor = color;
  91138. }
  91139. };
  91140. /**
  91141. * Exits VR and disposes of the vr experience helper
  91142. */
  91143. VRExperienceHelper.prototype.dispose = function () {
  91144. if (this.isInVRMode) {
  91145. this.exitVR();
  91146. }
  91147. if (this._postProcessMove) {
  91148. this._postProcessMove.dispose();
  91149. }
  91150. if (this._webVRCamera) {
  91151. this._webVRCamera.dispose();
  91152. }
  91153. if (this._vrDeviceOrientationCamera) {
  91154. this._vrDeviceOrientationCamera.dispose();
  91155. }
  91156. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91157. document.body.removeChild(this._btnVR);
  91158. }
  91159. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91160. this._deviceOrientationCamera.dispose();
  91161. }
  91162. if (this._cameraGazer) {
  91163. this._cameraGazer.dispose();
  91164. }
  91165. if (this.leftController) {
  91166. this.leftController.dispose();
  91167. }
  91168. if (this.rightController) {
  91169. this.rightController.dispose();
  91170. }
  91171. if (this._teleportationTarget) {
  91172. this._teleportationTarget.dispose();
  91173. }
  91174. this._floorMeshesCollection = [];
  91175. document.removeEventListener("keydown", this._onKeyDown);
  91176. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91177. window.removeEventListener("resize", this._onResize);
  91178. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91179. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91180. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91181. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91182. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91183. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91184. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91185. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91186. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91187. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91188. this._scene.unregisterBeforeRender(this.beforeRender);
  91189. };
  91190. /**
  91191. * Gets the name of the VRExperienceHelper class
  91192. * @returns "VRExperienceHelper"
  91193. */
  91194. VRExperienceHelper.prototype.getClassName = function () {
  91195. return "VRExperienceHelper";
  91196. };
  91197. return VRExperienceHelper;
  91198. }());
  91199. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91200. })(BABYLON || (BABYLON = {}));
  91201. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91202. // Mainly based on these 2 articles :
  91203. // 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
  91204. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91205. var BABYLON;
  91206. (function (BABYLON) {
  91207. /**
  91208. * Defines the potential axis of a Joystick
  91209. */
  91210. var JoystickAxis;
  91211. (function (JoystickAxis) {
  91212. /** X axis */
  91213. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91214. /** Y axis */
  91215. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91216. /** Z axis */
  91217. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91218. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91219. /**
  91220. * Class used to define virtual joystick (used in touch mode)
  91221. */
  91222. var VirtualJoystick = /** @class */ (function () {
  91223. /**
  91224. * Creates a new virtual joystick
  91225. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91226. */
  91227. function VirtualJoystick(leftJoystick) {
  91228. var _this = this;
  91229. if (leftJoystick) {
  91230. this._leftJoystick = true;
  91231. }
  91232. else {
  91233. this._leftJoystick = false;
  91234. }
  91235. VirtualJoystick._globalJoystickIndex++;
  91236. // By default left & right arrow keys are moving the X
  91237. // and up & down keys are moving the Y
  91238. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91239. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91240. this.reverseLeftRight = false;
  91241. this.reverseUpDown = false;
  91242. // collections of pointers
  91243. this._touches = new BABYLON.StringDictionary();
  91244. this.deltaPosition = BABYLON.Vector3.Zero();
  91245. this._joystickSensibility = 25;
  91246. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91247. this._onResize = function (evt) {
  91248. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91249. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91250. if (VirtualJoystick.vjCanvas) {
  91251. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91252. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91253. }
  91254. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91255. };
  91256. // injecting a canvas element on top of the canvas 3D game
  91257. if (!VirtualJoystick.vjCanvas) {
  91258. window.addEventListener("resize", this._onResize, false);
  91259. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91260. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91261. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91262. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91263. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91264. VirtualJoystick.vjCanvas.style.width = "100%";
  91265. VirtualJoystick.vjCanvas.style.height = "100%";
  91266. VirtualJoystick.vjCanvas.style.position = "absolute";
  91267. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91268. VirtualJoystick.vjCanvas.style.top = "0px";
  91269. VirtualJoystick.vjCanvas.style.left = "0px";
  91270. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91271. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91272. // Support for jQuery PEP polyfill
  91273. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91274. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91275. if (!context) {
  91276. throw new Error("Unable to create canvas for virtual joystick");
  91277. }
  91278. VirtualJoystick.vjCanvasContext = context;
  91279. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91280. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91281. document.body.appendChild(VirtualJoystick.vjCanvas);
  91282. }
  91283. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91284. this.pressed = false;
  91285. // default joystick color
  91286. this._joystickColor = "cyan";
  91287. this._joystickPointerID = -1;
  91288. // current joystick position
  91289. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91290. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91291. // origin joystick position
  91292. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91293. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91294. this._onPointerDownHandlerRef = function (evt) {
  91295. _this._onPointerDown(evt);
  91296. };
  91297. this._onPointerMoveHandlerRef = function (evt) {
  91298. _this._onPointerMove(evt);
  91299. };
  91300. this._onPointerUpHandlerRef = function (evt) {
  91301. _this._onPointerUp(evt);
  91302. };
  91303. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91304. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91305. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91306. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91307. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91308. evt.preventDefault(); // Disables system menu
  91309. }, false);
  91310. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91311. }
  91312. /**
  91313. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91314. * @param newJoystickSensibility defines the new sensibility
  91315. */
  91316. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91317. this._joystickSensibility = newJoystickSensibility;
  91318. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91319. };
  91320. VirtualJoystick.prototype._onPointerDown = function (e) {
  91321. var positionOnScreenCondition;
  91322. e.preventDefault();
  91323. if (this._leftJoystick === true) {
  91324. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91325. }
  91326. else {
  91327. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91328. }
  91329. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91330. // First contact will be dedicated to the virtual joystick
  91331. this._joystickPointerID = e.pointerId;
  91332. this._joystickPointerStartPos.x = e.clientX;
  91333. this._joystickPointerStartPos.y = e.clientY;
  91334. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91335. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91336. this._deltaJoystickVector.x = 0;
  91337. this._deltaJoystickVector.y = 0;
  91338. this.pressed = true;
  91339. this._touches.add(e.pointerId.toString(), e);
  91340. }
  91341. else {
  91342. // You can only trigger the action buttons with a joystick declared
  91343. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91344. this._action();
  91345. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91346. }
  91347. }
  91348. };
  91349. VirtualJoystick.prototype._onPointerMove = function (e) {
  91350. // If the current pointer is the one associated to the joystick (first touch contact)
  91351. if (this._joystickPointerID == e.pointerId) {
  91352. this._joystickPointerPos.x = e.clientX;
  91353. this._joystickPointerPos.y = e.clientY;
  91354. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91355. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91356. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91357. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91358. switch (this._axisTargetedByLeftAndRight) {
  91359. case JoystickAxis.X:
  91360. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91361. break;
  91362. case JoystickAxis.Y:
  91363. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91364. break;
  91365. case JoystickAxis.Z:
  91366. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91367. break;
  91368. }
  91369. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91370. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91371. switch (this._axisTargetedByUpAndDown) {
  91372. case JoystickAxis.X:
  91373. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91374. break;
  91375. case JoystickAxis.Y:
  91376. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91377. break;
  91378. case JoystickAxis.Z:
  91379. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91380. break;
  91381. }
  91382. }
  91383. else {
  91384. var data = this._touches.get(e.pointerId.toString());
  91385. if (data) {
  91386. data.x = e.clientX;
  91387. data.y = e.clientY;
  91388. }
  91389. }
  91390. };
  91391. VirtualJoystick.prototype._onPointerUp = function (e) {
  91392. if (this._joystickPointerID == e.pointerId) {
  91393. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91394. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91395. this._joystickPointerID = -1;
  91396. this.pressed = false;
  91397. }
  91398. else {
  91399. var touch = this._touches.get(e.pointerId.toString());
  91400. if (touch) {
  91401. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91402. }
  91403. }
  91404. this._deltaJoystickVector.x = 0;
  91405. this._deltaJoystickVector.y = 0;
  91406. this._touches.remove(e.pointerId.toString());
  91407. };
  91408. /**
  91409. * Change the color of the virtual joystick
  91410. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91411. */
  91412. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91413. this._joystickColor = newColor;
  91414. };
  91415. /**
  91416. * Defines a callback to call when the joystick is touched
  91417. * @param action defines the callback
  91418. */
  91419. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91420. this._action = action;
  91421. };
  91422. /**
  91423. * Defines which axis you'd like to control for left & right
  91424. * @param axis defines the axis to use
  91425. */
  91426. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91427. switch (axis) {
  91428. case JoystickAxis.X:
  91429. case JoystickAxis.Y:
  91430. case JoystickAxis.Z:
  91431. this._axisTargetedByLeftAndRight = axis;
  91432. break;
  91433. default:
  91434. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91435. break;
  91436. }
  91437. };
  91438. /**
  91439. * Defines which axis you'd like to control for up & down
  91440. * @param axis defines the axis to use
  91441. */
  91442. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91443. switch (axis) {
  91444. case JoystickAxis.X:
  91445. case JoystickAxis.Y:
  91446. case JoystickAxis.Z:
  91447. this._axisTargetedByUpAndDown = axis;
  91448. break;
  91449. default:
  91450. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91451. break;
  91452. }
  91453. };
  91454. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91455. var _this = this;
  91456. if (this.pressed) {
  91457. this._touches.forEach(function (key, touch) {
  91458. if (touch.pointerId === _this._joystickPointerID) {
  91459. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91460. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91461. VirtualJoystick.vjCanvasContext.beginPath();
  91462. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91463. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91464. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91465. VirtualJoystick.vjCanvasContext.stroke();
  91466. VirtualJoystick.vjCanvasContext.closePath();
  91467. VirtualJoystick.vjCanvasContext.beginPath();
  91468. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91469. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91470. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91471. VirtualJoystick.vjCanvasContext.stroke();
  91472. VirtualJoystick.vjCanvasContext.closePath();
  91473. VirtualJoystick.vjCanvasContext.beginPath();
  91474. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91475. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91476. VirtualJoystick.vjCanvasContext.stroke();
  91477. VirtualJoystick.vjCanvasContext.closePath();
  91478. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91479. }
  91480. else {
  91481. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91482. VirtualJoystick.vjCanvasContext.beginPath();
  91483. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91484. VirtualJoystick.vjCanvasContext.beginPath();
  91485. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91486. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91487. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91488. VirtualJoystick.vjCanvasContext.stroke();
  91489. VirtualJoystick.vjCanvasContext.closePath();
  91490. touch.prevX = touch.x;
  91491. touch.prevY = touch.y;
  91492. }
  91493. ;
  91494. });
  91495. }
  91496. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91497. };
  91498. /**
  91499. * Release internal HTML canvas
  91500. */
  91501. VirtualJoystick.prototype.releaseCanvas = function () {
  91502. if (VirtualJoystick.vjCanvas) {
  91503. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91504. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91505. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91506. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91507. window.removeEventListener("resize", this._onResize);
  91508. document.body.removeChild(VirtualJoystick.vjCanvas);
  91509. VirtualJoystick.vjCanvas = null;
  91510. }
  91511. };
  91512. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91513. VirtualJoystick._globalJoystickIndex = 0;
  91514. return VirtualJoystick;
  91515. }());
  91516. BABYLON.VirtualJoystick = VirtualJoystick;
  91517. })(BABYLON || (BABYLON = {}));
  91518. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91519. var BABYLON;
  91520. (function (BABYLON) {
  91521. // We're mainly based on the logic defined into the FreeCamera code
  91522. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91523. __extends(VirtualJoysticksCamera, _super);
  91524. function VirtualJoysticksCamera(name, position, scene) {
  91525. var _this = _super.call(this, name, position, scene) || this;
  91526. _this.inputs.addVirtualJoystick();
  91527. return _this;
  91528. }
  91529. VirtualJoysticksCamera.prototype.getClassName = function () {
  91530. return "VirtualJoysticksCamera";
  91531. };
  91532. return VirtualJoysticksCamera;
  91533. }(BABYLON.FreeCamera));
  91534. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91535. })(BABYLON || (BABYLON = {}));
  91536. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91537. var BABYLON;
  91538. (function (BABYLON) {
  91539. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91540. function FreeCameraVirtualJoystickInput() {
  91541. }
  91542. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91543. return this._leftjoystick;
  91544. };
  91545. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91546. return this._rightjoystick;
  91547. };
  91548. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91549. if (this._leftjoystick) {
  91550. var camera = this.camera;
  91551. var speed = camera._computeLocalCameraSpeed() * 50;
  91552. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91553. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91554. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91555. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91556. if (!this._leftjoystick.pressed) {
  91557. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91558. }
  91559. if (!this._rightjoystick.pressed) {
  91560. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91561. }
  91562. }
  91563. };
  91564. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91565. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91566. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91567. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91568. this._leftjoystick.setJoystickSensibility(0.15);
  91569. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91570. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91571. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91572. this._rightjoystick.reverseUpDown = true;
  91573. this._rightjoystick.setJoystickSensibility(0.05);
  91574. this._rightjoystick.setJoystickColor("yellow");
  91575. };
  91576. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91577. this._leftjoystick.releaseCanvas();
  91578. this._rightjoystick.releaseCanvas();
  91579. };
  91580. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91581. return "FreeCameraVirtualJoystickInput";
  91582. };
  91583. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91584. return "virtualJoystick";
  91585. };
  91586. return FreeCameraVirtualJoystickInput;
  91587. }());
  91588. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91589. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91590. })(BABYLON || (BABYLON = {}));
  91591. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91592. var BABYLON;
  91593. (function (BABYLON) {
  91594. var SimplificationSettings = /** @class */ (function () {
  91595. function SimplificationSettings(quality, distance, optimizeMesh) {
  91596. this.quality = quality;
  91597. this.distance = distance;
  91598. this.optimizeMesh = optimizeMesh;
  91599. }
  91600. return SimplificationSettings;
  91601. }());
  91602. BABYLON.SimplificationSettings = SimplificationSettings;
  91603. var SimplificationQueue = /** @class */ (function () {
  91604. function SimplificationQueue() {
  91605. this.running = false;
  91606. this._simplificationArray = [];
  91607. }
  91608. SimplificationQueue.prototype.addTask = function (task) {
  91609. this._simplificationArray.push(task);
  91610. };
  91611. SimplificationQueue.prototype.executeNext = function () {
  91612. var task = this._simplificationArray.pop();
  91613. if (task) {
  91614. this.running = true;
  91615. this.runSimplification(task);
  91616. }
  91617. else {
  91618. this.running = false;
  91619. }
  91620. };
  91621. SimplificationQueue.prototype.runSimplification = function (task) {
  91622. var _this = this;
  91623. if (task.parallelProcessing) {
  91624. //parallel simplifier
  91625. task.settings.forEach(function (setting) {
  91626. var simplifier = _this.getSimplifier(task);
  91627. simplifier.simplify(setting, function (newMesh) {
  91628. task.mesh.addLODLevel(setting.distance, newMesh);
  91629. newMesh.isVisible = true;
  91630. //check if it is the last
  91631. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91632. //all done, run the success callback.
  91633. task.successCallback();
  91634. }
  91635. _this.executeNext();
  91636. });
  91637. });
  91638. }
  91639. else {
  91640. //single simplifier.
  91641. var simplifier = this.getSimplifier(task);
  91642. var runDecimation = function (setting, callback) {
  91643. simplifier.simplify(setting, function (newMesh) {
  91644. task.mesh.addLODLevel(setting.distance, newMesh);
  91645. newMesh.isVisible = true;
  91646. //run the next quality level
  91647. callback();
  91648. });
  91649. };
  91650. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  91651. runDecimation(task.settings[loop.index], function () {
  91652. loop.executeNext();
  91653. });
  91654. }, function () {
  91655. //execution ended, run the success callback.
  91656. if (task.successCallback) {
  91657. task.successCallback();
  91658. }
  91659. _this.executeNext();
  91660. });
  91661. }
  91662. };
  91663. SimplificationQueue.prototype.getSimplifier = function (task) {
  91664. switch (task.simplificationType) {
  91665. case SimplificationType.QUADRATIC:
  91666. default:
  91667. return new QuadraticErrorSimplification(task.mesh);
  91668. }
  91669. };
  91670. return SimplificationQueue;
  91671. }());
  91672. BABYLON.SimplificationQueue = SimplificationQueue;
  91673. /**
  91674. * The implemented types of simplification
  91675. * At the moment only Quadratic Error Decimation is implemented
  91676. */
  91677. var SimplificationType;
  91678. (function (SimplificationType) {
  91679. /** Quadratic error decimation */
  91680. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91681. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91682. var DecimationTriangle = /** @class */ (function () {
  91683. function DecimationTriangle(vertices) {
  91684. this.vertices = vertices;
  91685. this.error = new Array(4);
  91686. this.deleted = false;
  91687. this.isDirty = false;
  91688. this.deletePending = false;
  91689. this.borderFactor = 0;
  91690. }
  91691. return DecimationTriangle;
  91692. }());
  91693. BABYLON.DecimationTriangle = DecimationTriangle;
  91694. var DecimationVertex = /** @class */ (function () {
  91695. function DecimationVertex(position, id) {
  91696. this.position = position;
  91697. this.id = id;
  91698. this.isBorder = true;
  91699. this.q = new QuadraticMatrix();
  91700. this.triangleCount = 0;
  91701. this.triangleStart = 0;
  91702. this.originalOffsets = [];
  91703. }
  91704. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91705. this.position.copyFrom(newPosition);
  91706. };
  91707. return DecimationVertex;
  91708. }());
  91709. BABYLON.DecimationVertex = DecimationVertex;
  91710. var QuadraticMatrix = /** @class */ (function () {
  91711. function QuadraticMatrix(data) {
  91712. this.data = new Array(10);
  91713. for (var i = 0; i < 10; ++i) {
  91714. if (data && data[i]) {
  91715. this.data[i] = data[i];
  91716. }
  91717. else {
  91718. this.data[i] = 0;
  91719. }
  91720. }
  91721. }
  91722. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91723. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91724. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91725. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91726. return det;
  91727. };
  91728. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91729. for (var i = 0; i < 10; ++i) {
  91730. this.data[i] += matrix.data[i];
  91731. }
  91732. };
  91733. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91734. for (var i = 0; i < 10; ++i) {
  91735. this.data[i] += data[i];
  91736. }
  91737. };
  91738. QuadraticMatrix.prototype.add = function (matrix) {
  91739. var m = new QuadraticMatrix();
  91740. for (var i = 0; i < 10; ++i) {
  91741. m.data[i] = this.data[i] + matrix.data[i];
  91742. }
  91743. return m;
  91744. };
  91745. QuadraticMatrix.FromData = function (a, b, c, d) {
  91746. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91747. };
  91748. //returning an array to avoid garbage collection
  91749. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91750. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91751. };
  91752. return QuadraticMatrix;
  91753. }());
  91754. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91755. var Reference = /** @class */ (function () {
  91756. function Reference(vertexId, triangleId) {
  91757. this.vertexId = vertexId;
  91758. this.triangleId = triangleId;
  91759. }
  91760. return Reference;
  91761. }());
  91762. BABYLON.Reference = Reference;
  91763. /**
  91764. * An implementation of the Quadratic Error simplification algorithm.
  91765. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91766. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91767. * @author RaananW
  91768. */
  91769. var QuadraticErrorSimplification = /** @class */ (function () {
  91770. function QuadraticErrorSimplification(_mesh) {
  91771. this._mesh = _mesh;
  91772. this.syncIterations = 5000;
  91773. this.aggressiveness = 7;
  91774. this.decimationIterations = 100;
  91775. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91776. }
  91777. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91778. var _this = this;
  91779. this.initDecimatedMesh();
  91780. //iterating through the submeshes array, one after the other.
  91781. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91782. _this.initWithMesh(loop.index, function () {
  91783. _this.runDecimation(settings, loop.index, function () {
  91784. loop.executeNext();
  91785. });
  91786. }, settings.optimizeMesh);
  91787. }, function () {
  91788. setTimeout(function () {
  91789. successCallback(_this._reconstructedMesh);
  91790. }, 0);
  91791. });
  91792. };
  91793. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91794. var _this = this;
  91795. var targetCount = ~~(this.triangles.length * settings.quality);
  91796. var deletedTriangles = 0;
  91797. var triangleCount = this.triangles.length;
  91798. var iterationFunction = function (iteration, callback) {
  91799. setTimeout(function () {
  91800. if (iteration % 5 === 0) {
  91801. _this.updateMesh(iteration === 0);
  91802. }
  91803. for (var i = 0; i < _this.triangles.length; ++i) {
  91804. _this.triangles[i].isDirty = false;
  91805. }
  91806. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91807. var trianglesIterator = function (i) {
  91808. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91809. var t = _this.triangles[tIdx];
  91810. if (!t)
  91811. return;
  91812. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91813. return;
  91814. }
  91815. for (var j = 0; j < 3; ++j) {
  91816. if (t.error[j] < threshold) {
  91817. var deleted0 = [];
  91818. var deleted1 = [];
  91819. var v0 = t.vertices[j];
  91820. var v1 = t.vertices[(j + 1) % 3];
  91821. if (v0.isBorder || v1.isBorder)
  91822. continue;
  91823. var p = BABYLON.Vector3.Zero();
  91824. var n = BABYLON.Vector3.Zero();
  91825. var uv = BABYLON.Vector2.Zero();
  91826. var color = new BABYLON.Color4(0, 0, 0, 1);
  91827. _this.calculateError(v0, v1, p, n, uv, color);
  91828. var delTr = new Array();
  91829. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91830. continue;
  91831. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91832. continue;
  91833. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91834. continue;
  91835. var uniqueArray = new Array();
  91836. delTr.forEach(function (deletedT) {
  91837. if (uniqueArray.indexOf(deletedT) === -1) {
  91838. deletedT.deletePending = true;
  91839. uniqueArray.push(deletedT);
  91840. }
  91841. });
  91842. if (uniqueArray.length % 2 !== 0) {
  91843. continue;
  91844. }
  91845. v0.q = v1.q.add(v0.q);
  91846. v0.updatePosition(p);
  91847. var tStart = _this.references.length;
  91848. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  91849. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  91850. var tCount = _this.references.length - tStart;
  91851. if (tCount <= v0.triangleCount) {
  91852. if (tCount) {
  91853. for (var c = 0; c < tCount; c++) {
  91854. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  91855. }
  91856. }
  91857. }
  91858. else {
  91859. v0.triangleStart = tStart;
  91860. }
  91861. v0.triangleCount = tCount;
  91862. break;
  91863. }
  91864. }
  91865. };
  91866. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  91867. }, 0);
  91868. };
  91869. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  91870. if (triangleCount - deletedTriangles <= targetCount)
  91871. loop.breakLoop();
  91872. else {
  91873. iterationFunction(loop.index, function () {
  91874. loop.executeNext();
  91875. });
  91876. }
  91877. }, function () {
  91878. setTimeout(function () {
  91879. //reconstruct this part of the mesh
  91880. _this.reconstructMesh(submeshIndex);
  91881. successCallback();
  91882. }, 0);
  91883. });
  91884. };
  91885. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  91886. var _this = this;
  91887. this.vertices = [];
  91888. this.triangles = [];
  91889. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91890. var indices = this._mesh.getIndices();
  91891. var submesh = this._mesh.subMeshes[submeshIndex];
  91892. var findInVertices = function (positionToSearch) {
  91893. if (optimizeMesh) {
  91894. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  91895. if (_this.vertices[ii].position.equals(positionToSearch)) {
  91896. return _this.vertices[ii];
  91897. }
  91898. }
  91899. }
  91900. return null;
  91901. };
  91902. var vertexReferences = [];
  91903. var vertexInit = function (i) {
  91904. if (!positionData) {
  91905. return;
  91906. }
  91907. var offset = i + submesh.verticesStart;
  91908. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  91909. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  91910. vertex.originalOffsets.push(offset);
  91911. if (vertex.id === _this.vertices.length) {
  91912. _this.vertices.push(vertex);
  91913. }
  91914. vertexReferences.push(vertex.id);
  91915. };
  91916. //var totalVertices = mesh.getTotalVertices();
  91917. var totalVertices = submesh.verticesCount;
  91918. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  91919. var indicesInit = function (i) {
  91920. if (!indices) {
  91921. return;
  91922. }
  91923. var offset = (submesh.indexStart / 3) + i;
  91924. var pos = (offset * 3);
  91925. var i0 = indices[pos + 0];
  91926. var i1 = indices[pos + 1];
  91927. var i2 = indices[pos + 2];
  91928. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  91929. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  91930. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  91931. var triangle = new DecimationTriangle([v0, v1, v2]);
  91932. triangle.originalOffset = pos;
  91933. _this.triangles.push(triangle);
  91934. };
  91935. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  91936. _this.init(callback);
  91937. });
  91938. });
  91939. };
  91940. QuadraticErrorSimplification.prototype.init = function (callback) {
  91941. var _this = this;
  91942. var triangleInit1 = function (i) {
  91943. var t = _this.triangles[i];
  91944. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  91945. for (var j = 0; j < 3; j++) {
  91946. 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))));
  91947. }
  91948. };
  91949. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  91950. var triangleInit2 = function (i) {
  91951. var t = _this.triangles[i];
  91952. for (var j = 0; j < 3; ++j) {
  91953. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  91954. }
  91955. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  91956. };
  91957. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  91958. callback();
  91959. });
  91960. });
  91961. };
  91962. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  91963. var newTriangles = [];
  91964. var i;
  91965. for (i = 0; i < this.vertices.length; ++i) {
  91966. this.vertices[i].triangleCount = 0;
  91967. }
  91968. var t;
  91969. var j;
  91970. for (i = 0; i < this.triangles.length; ++i) {
  91971. if (!this.triangles[i].deleted) {
  91972. t = this.triangles[i];
  91973. for (j = 0; j < 3; ++j) {
  91974. t.vertices[j].triangleCount = 1;
  91975. }
  91976. newTriangles.push(t);
  91977. }
  91978. }
  91979. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  91980. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  91981. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  91982. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  91983. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  91984. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  91985. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  91986. var vertexCount = 0;
  91987. for (i = 0; i < this.vertices.length; ++i) {
  91988. var vertex = this.vertices[i];
  91989. vertex.id = vertexCount;
  91990. if (vertex.triangleCount) {
  91991. vertex.originalOffsets.forEach(function (originalOffset) {
  91992. if (!normalData) {
  91993. return;
  91994. }
  91995. newPositionData.push(vertex.position.x);
  91996. newPositionData.push(vertex.position.y);
  91997. newPositionData.push(vertex.position.z);
  91998. newNormalData.push(normalData[originalOffset * 3]);
  91999. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  92000. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  92001. if (uvs && uvs.length) {
  92002. newUVsData.push(uvs[(originalOffset * 2)]);
  92003. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  92004. }
  92005. else if (colorsData && colorsData.length) {
  92006. newColorsData.push(colorsData[(originalOffset * 4)]);
  92007. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  92008. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  92009. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  92010. }
  92011. ++vertexCount;
  92012. });
  92013. }
  92014. }
  92015. var startingIndex = this._reconstructedMesh.getTotalIndices();
  92016. var startingVertex = this._reconstructedMesh.getTotalVertices();
  92017. var submeshesArray = this._reconstructedMesh.subMeshes;
  92018. this._reconstructedMesh.subMeshes = [];
  92019. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  92020. var originalIndices = this._mesh.getIndices();
  92021. for (i = 0; i < newTriangles.length; ++i) {
  92022. t = newTriangles[i]; //now get the new referencing point for each vertex
  92023. [0, 1, 2].forEach(function (idx) {
  92024. var id = originalIndices[t.originalOffset + idx];
  92025. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  92026. if (offset < 0)
  92027. offset = 0;
  92028. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  92029. });
  92030. }
  92031. //overwriting the old vertex buffers and indices.
  92032. this._reconstructedMesh.setIndices(newIndicesArray);
  92033. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92034. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92035. if (newUVsData.length > 0)
  92036. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92037. if (newColorsData.length > 0)
  92038. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92039. //create submesh
  92040. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92041. if (submeshIndex > 0) {
  92042. this._reconstructedMesh.subMeshes = [];
  92043. submeshesArray.forEach(function (submesh) {
  92044. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92045. });
  92046. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92047. }
  92048. };
  92049. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92050. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92051. this._reconstructedMesh.material = this._mesh.material;
  92052. this._reconstructedMesh.parent = this._mesh.parent;
  92053. this._reconstructedMesh.isVisible = false;
  92054. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92055. };
  92056. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92057. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92058. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92059. if (t.deleted)
  92060. continue;
  92061. var s = this.references[vertex1.triangleStart + i].vertexId;
  92062. var v1 = t.vertices[(s + 1) % 3];
  92063. var v2 = t.vertices[(s + 2) % 3];
  92064. if ((v1 === vertex2 || v2 === vertex2)) {
  92065. deletedArray[i] = true;
  92066. delTr.push(t);
  92067. continue;
  92068. }
  92069. var d1 = v1.position.subtract(point);
  92070. d1 = d1.normalize();
  92071. var d2 = v2.position.subtract(point);
  92072. d2 = d2.normalize();
  92073. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92074. return true;
  92075. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92076. deletedArray[i] = false;
  92077. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92078. return true;
  92079. }
  92080. return false;
  92081. };
  92082. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92083. var newDeleted = deletedTriangles;
  92084. for (var i = 0; i < vertex.triangleCount; ++i) {
  92085. var ref = this.references[vertex.triangleStart + i];
  92086. var t = this.triangles[ref.triangleId];
  92087. if (t.deleted)
  92088. continue;
  92089. if (deletedArray[i] && t.deletePending) {
  92090. t.deleted = true;
  92091. newDeleted++;
  92092. continue;
  92093. }
  92094. t.vertices[ref.vertexId] = origVertex;
  92095. t.isDirty = true;
  92096. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92097. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92098. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92099. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92100. this.references.push(ref);
  92101. }
  92102. return newDeleted;
  92103. };
  92104. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92105. for (var i = 0; i < this.vertices.length; ++i) {
  92106. var vCount = [];
  92107. var vId = [];
  92108. var v = this.vertices[i];
  92109. var j;
  92110. for (j = 0; j < v.triangleCount; ++j) {
  92111. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92112. for (var ii = 0; ii < 3; ii++) {
  92113. var ofs = 0;
  92114. var vv = triangle.vertices[ii];
  92115. while (ofs < vCount.length) {
  92116. if (vId[ofs] === vv.id)
  92117. break;
  92118. ++ofs;
  92119. }
  92120. if (ofs === vCount.length) {
  92121. vCount.push(1);
  92122. vId.push(vv.id);
  92123. }
  92124. else {
  92125. vCount[ofs]++;
  92126. }
  92127. }
  92128. }
  92129. for (j = 0; j < vCount.length; ++j) {
  92130. if (vCount[j] === 1) {
  92131. this.vertices[vId[j]].isBorder = true;
  92132. }
  92133. else {
  92134. this.vertices[vId[j]].isBorder = false;
  92135. }
  92136. }
  92137. }
  92138. };
  92139. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92140. if (identifyBorders === void 0) { identifyBorders = false; }
  92141. var i;
  92142. if (!identifyBorders) {
  92143. var newTrianglesVector = [];
  92144. for (i = 0; i < this.triangles.length; ++i) {
  92145. if (!this.triangles[i].deleted) {
  92146. newTrianglesVector.push(this.triangles[i]);
  92147. }
  92148. }
  92149. this.triangles = newTrianglesVector;
  92150. }
  92151. for (i = 0; i < this.vertices.length; ++i) {
  92152. this.vertices[i].triangleCount = 0;
  92153. this.vertices[i].triangleStart = 0;
  92154. }
  92155. var t;
  92156. var j;
  92157. var v;
  92158. for (i = 0; i < this.triangles.length; ++i) {
  92159. t = this.triangles[i];
  92160. for (j = 0; j < 3; ++j) {
  92161. v = t.vertices[j];
  92162. v.triangleCount++;
  92163. }
  92164. }
  92165. var tStart = 0;
  92166. for (i = 0; i < this.vertices.length; ++i) {
  92167. this.vertices[i].triangleStart = tStart;
  92168. tStart += this.vertices[i].triangleCount;
  92169. this.vertices[i].triangleCount = 0;
  92170. }
  92171. var newReferences = new Array(this.triangles.length * 3);
  92172. for (i = 0; i < this.triangles.length; ++i) {
  92173. t = this.triangles[i];
  92174. for (j = 0; j < 3; ++j) {
  92175. v = t.vertices[j];
  92176. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92177. v.triangleCount++;
  92178. }
  92179. }
  92180. this.references = newReferences;
  92181. if (identifyBorders) {
  92182. this.identifyBorder();
  92183. }
  92184. };
  92185. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92186. var x = point.x;
  92187. var y = point.y;
  92188. var z = point.z;
  92189. 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
  92190. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92191. };
  92192. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92193. var q = vertex1.q.add(vertex2.q);
  92194. var border = vertex1.isBorder && vertex2.isBorder;
  92195. var error = 0;
  92196. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92197. if (qDet !== 0 && !border) {
  92198. if (!pointResult) {
  92199. pointResult = BABYLON.Vector3.Zero();
  92200. }
  92201. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92202. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92203. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92204. error = this.vertexError(q, pointResult);
  92205. }
  92206. else {
  92207. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92208. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92209. var error1 = this.vertexError(q, vertex1.position);
  92210. var error2 = this.vertexError(q, vertex2.position);
  92211. var error3 = this.vertexError(q, p3);
  92212. error = Math.min(error1, error2, error3);
  92213. if (error === error1) {
  92214. if (pointResult) {
  92215. pointResult.copyFrom(vertex1.position);
  92216. }
  92217. }
  92218. else if (error === error2) {
  92219. if (pointResult) {
  92220. pointResult.copyFrom(vertex2.position);
  92221. }
  92222. }
  92223. else {
  92224. if (pointResult) {
  92225. pointResult.copyFrom(p3);
  92226. }
  92227. }
  92228. }
  92229. return error;
  92230. };
  92231. return QuadraticErrorSimplification;
  92232. }());
  92233. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92234. })(BABYLON || (BABYLON = {}));
  92235. //# sourceMappingURL=babylon.meshSimplification.js.map
  92236. var BABYLON;
  92237. (function (BABYLON) {
  92238. var MeshLODLevel = /** @class */ (function () {
  92239. function MeshLODLevel(distance, mesh) {
  92240. this.distance = distance;
  92241. this.mesh = mesh;
  92242. }
  92243. return MeshLODLevel;
  92244. }());
  92245. BABYLON.MeshLODLevel = MeshLODLevel;
  92246. })(BABYLON || (BABYLON = {}));
  92247. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92248. var BABYLON;
  92249. (function (BABYLON) {
  92250. /**
  92251. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92252. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92253. */
  92254. var SceneOptimization = /** @class */ (function () {
  92255. /**
  92256. * Creates the SceneOptimization object
  92257. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92258. * @param desc defines the description associated with the optimization
  92259. */
  92260. function SceneOptimization(
  92261. /**
  92262. * Defines the priority of this optimization (0 by default which means first in the list)
  92263. */
  92264. priority) {
  92265. if (priority === void 0) { priority = 0; }
  92266. this.priority = priority;
  92267. }
  92268. /**
  92269. * Gets a string describing the action executed by the current optimization
  92270. * @returns description string
  92271. */
  92272. SceneOptimization.prototype.getDescription = function () {
  92273. return "";
  92274. };
  92275. /**
  92276. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92277. * @param scene defines the current scene where to apply this optimization
  92278. * @param optimizer defines the current optimizer
  92279. * @returns true if everything that can be done was applied
  92280. */
  92281. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92282. return true;
  92283. };
  92284. ;
  92285. return SceneOptimization;
  92286. }());
  92287. BABYLON.SceneOptimization = SceneOptimization;
  92288. /**
  92289. * Defines an optimization used to reduce the size of render target textures
  92290. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92291. */
  92292. var TextureOptimization = /** @class */ (function (_super) {
  92293. __extends(TextureOptimization, _super);
  92294. /**
  92295. * Creates the TextureOptimization object
  92296. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92297. * @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
  92298. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92299. */
  92300. function TextureOptimization(
  92301. /**
  92302. * Defines the priority of this optimization (0 by default which means first in the list)
  92303. */
  92304. priority,
  92305. /**
  92306. * 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
  92307. */
  92308. maximumSize,
  92309. /**
  92310. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92311. */
  92312. step) {
  92313. if (priority === void 0) { priority = 0; }
  92314. if (maximumSize === void 0) { maximumSize = 1024; }
  92315. if (step === void 0) { step = 0.5; }
  92316. var _this = _super.call(this, priority) || this;
  92317. _this.priority = priority;
  92318. _this.maximumSize = maximumSize;
  92319. _this.step = step;
  92320. return _this;
  92321. }
  92322. /**
  92323. * Gets a string describing the action executed by the current optimization
  92324. * @returns description string
  92325. */
  92326. TextureOptimization.prototype.getDescription = function () {
  92327. return "Reducing render target texture size to " + this.maximumSize;
  92328. };
  92329. /**
  92330. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92331. * @param scene defines the current scene where to apply this optimization
  92332. * @param optimizer defines the current optimizer
  92333. * @returns true if everything that can be done was applied
  92334. */
  92335. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92336. var allDone = true;
  92337. for (var index = 0; index < scene.textures.length; index++) {
  92338. var texture = scene.textures[index];
  92339. if (!texture.canRescale || texture.getContext) {
  92340. continue;
  92341. }
  92342. var currentSize = texture.getSize();
  92343. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92344. if (maxDimension > this.maximumSize) {
  92345. texture.scale(this.step);
  92346. allDone = false;
  92347. }
  92348. }
  92349. return allDone;
  92350. };
  92351. return TextureOptimization;
  92352. }(SceneOptimization));
  92353. BABYLON.TextureOptimization = TextureOptimization;
  92354. /**
  92355. * Defines an optimization used to increase or decrease the rendering resolution
  92356. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92357. */
  92358. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92359. __extends(HardwareScalingOptimization, _super);
  92360. /**
  92361. * Creates the HardwareScalingOptimization object
  92362. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92363. * @param maximumScale defines the maximum scale to use (2 by default)
  92364. * @param step defines the step to use between two passes (0.5 by default)
  92365. */
  92366. function HardwareScalingOptimization(
  92367. /**
  92368. * Defines the priority of this optimization (0 by default which means first in the list)
  92369. */
  92370. priority,
  92371. /**
  92372. * Defines the maximum scale to use (2 by default)
  92373. */
  92374. maximumScale,
  92375. /**
  92376. * Defines the step to use between two passes (0.5 by default)
  92377. */
  92378. step) {
  92379. if (priority === void 0) { priority = 0; }
  92380. if (maximumScale === void 0) { maximumScale = 2; }
  92381. if (step === void 0) { step = 0.25; }
  92382. var _this = _super.call(this, priority) || this;
  92383. _this.priority = priority;
  92384. _this.maximumScale = maximumScale;
  92385. _this.step = step;
  92386. _this._currentScale = -1;
  92387. _this._directionOffset = 1;
  92388. return _this;
  92389. }
  92390. /**
  92391. * Gets a string describing the action executed by the current optimization
  92392. * @return description string
  92393. */
  92394. HardwareScalingOptimization.prototype.getDescription = function () {
  92395. return "Setting hardware scaling level to " + this._currentScale;
  92396. };
  92397. /**
  92398. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92399. * @param scene defines the current scene where to apply this optimization
  92400. * @param optimizer defines the current optimizer
  92401. * @returns true if everything that can be done was applied
  92402. */
  92403. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92404. if (this._currentScale === -1) {
  92405. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92406. if (this._currentScale > this.maximumScale) {
  92407. this._directionOffset = -1;
  92408. }
  92409. }
  92410. this._currentScale += this._directionOffset * this.step;
  92411. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92412. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92413. };
  92414. ;
  92415. return HardwareScalingOptimization;
  92416. }(SceneOptimization));
  92417. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92418. /**
  92419. * Defines an optimization used to remove shadows
  92420. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92421. */
  92422. var ShadowsOptimization = /** @class */ (function (_super) {
  92423. __extends(ShadowsOptimization, _super);
  92424. function ShadowsOptimization() {
  92425. return _super !== null && _super.apply(this, arguments) || this;
  92426. }
  92427. /**
  92428. * Gets a string describing the action executed by the current optimization
  92429. * @return description string
  92430. */
  92431. ShadowsOptimization.prototype.getDescription = function () {
  92432. return "Turning shadows on/off";
  92433. };
  92434. /**
  92435. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92436. * @param scene defines the current scene where to apply this optimization
  92437. * @param optimizer defines the current optimizer
  92438. * @returns true if everything that can be done was applied
  92439. */
  92440. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92441. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92442. return true;
  92443. };
  92444. ;
  92445. return ShadowsOptimization;
  92446. }(SceneOptimization));
  92447. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92448. /**
  92449. * Defines an optimization used to turn post-processes off
  92450. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92451. */
  92452. var PostProcessesOptimization = /** @class */ (function (_super) {
  92453. __extends(PostProcessesOptimization, _super);
  92454. function PostProcessesOptimization() {
  92455. return _super !== null && _super.apply(this, arguments) || this;
  92456. }
  92457. /**
  92458. * Gets a string describing the action executed by the current optimization
  92459. * @return description string
  92460. */
  92461. PostProcessesOptimization.prototype.getDescription = function () {
  92462. return "Turning post-processes on/off";
  92463. };
  92464. /**
  92465. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92466. * @param scene defines the current scene where to apply this optimization
  92467. * @param optimizer defines the current optimizer
  92468. * @returns true if everything that can be done was applied
  92469. */
  92470. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92471. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92472. return true;
  92473. };
  92474. ;
  92475. return PostProcessesOptimization;
  92476. }(SceneOptimization));
  92477. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92478. /**
  92479. * Defines an optimization used to turn lens flares off
  92480. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92481. */
  92482. var LensFlaresOptimization = /** @class */ (function (_super) {
  92483. __extends(LensFlaresOptimization, _super);
  92484. function LensFlaresOptimization() {
  92485. return _super !== null && _super.apply(this, arguments) || this;
  92486. }
  92487. /**
  92488. * Gets a string describing the action executed by the current optimization
  92489. * @return description string
  92490. */
  92491. LensFlaresOptimization.prototype.getDescription = function () {
  92492. return "Turning lens flares on/off";
  92493. };
  92494. /**
  92495. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92496. * @param scene defines the current scene where to apply this optimization
  92497. * @param optimizer defines the current optimizer
  92498. * @returns true if everything that can be done was applied
  92499. */
  92500. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92501. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92502. return true;
  92503. };
  92504. ;
  92505. return LensFlaresOptimization;
  92506. }(SceneOptimization));
  92507. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92508. /**
  92509. * Defines an optimization based on user defined callback.
  92510. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92511. */
  92512. var CustomOptimization = /** @class */ (function (_super) {
  92513. __extends(CustomOptimization, _super);
  92514. function CustomOptimization() {
  92515. return _super !== null && _super.apply(this, arguments) || this;
  92516. }
  92517. /**
  92518. * Gets a string describing the action executed by the current optimization
  92519. * @returns description string
  92520. */
  92521. CustomOptimization.prototype.getDescription = function () {
  92522. if (this.onGetDescription) {
  92523. return this.onGetDescription();
  92524. }
  92525. return "Running user defined callback";
  92526. };
  92527. /**
  92528. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92529. * @param scene defines the current scene where to apply this optimization
  92530. * @param optimizer defines the current optimizer
  92531. * @returns true if everything that can be done was applied
  92532. */
  92533. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92534. if (this.onApply) {
  92535. return this.onApply(scene, optimizer);
  92536. }
  92537. return true;
  92538. };
  92539. ;
  92540. return CustomOptimization;
  92541. }(SceneOptimization));
  92542. BABYLON.CustomOptimization = CustomOptimization;
  92543. /**
  92544. * Defines an optimization used to turn particles off
  92545. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92546. */
  92547. var ParticlesOptimization = /** @class */ (function (_super) {
  92548. __extends(ParticlesOptimization, _super);
  92549. function ParticlesOptimization() {
  92550. return _super !== null && _super.apply(this, arguments) || this;
  92551. }
  92552. /**
  92553. * Gets a string describing the action executed by the current optimization
  92554. * @return description string
  92555. */
  92556. ParticlesOptimization.prototype.getDescription = function () {
  92557. return "Turning particles on/off";
  92558. };
  92559. /**
  92560. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92561. * @param scene defines the current scene where to apply this optimization
  92562. * @param optimizer defines the current optimizer
  92563. * @returns true if everything that can be done was applied
  92564. */
  92565. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92566. scene.particlesEnabled = optimizer.isInImprovementMode;
  92567. return true;
  92568. };
  92569. ;
  92570. return ParticlesOptimization;
  92571. }(SceneOptimization));
  92572. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92573. /**
  92574. * Defines an optimization used to turn render targets off
  92575. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92576. */
  92577. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92578. __extends(RenderTargetsOptimization, _super);
  92579. function RenderTargetsOptimization() {
  92580. return _super !== null && _super.apply(this, arguments) || this;
  92581. }
  92582. /**
  92583. * Gets a string describing the action executed by the current optimization
  92584. * @return description string
  92585. */
  92586. RenderTargetsOptimization.prototype.getDescription = function () {
  92587. return "Turning render targets off";
  92588. };
  92589. /**
  92590. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92591. * @param scene defines the current scene where to apply this optimization
  92592. * @param optimizer defines the current optimizer
  92593. * @returns true if everything that can be done was applied
  92594. */
  92595. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92596. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92597. return true;
  92598. };
  92599. ;
  92600. return RenderTargetsOptimization;
  92601. }(SceneOptimization));
  92602. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92603. /**
  92604. * Defines an optimization used to merge meshes with compatible materials
  92605. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92606. */
  92607. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92608. __extends(MergeMeshesOptimization, _super);
  92609. function MergeMeshesOptimization() {
  92610. var _this = _super !== null && _super.apply(this, arguments) || this;
  92611. _this._canBeMerged = function (abstractMesh) {
  92612. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92613. return false;
  92614. }
  92615. var mesh = abstractMesh;
  92616. if (!mesh.isVisible || !mesh.isEnabled()) {
  92617. return false;
  92618. }
  92619. if (mesh.instances.length > 0) {
  92620. return false;
  92621. }
  92622. if (mesh.skeleton || mesh.hasLODLevels) {
  92623. return false;
  92624. }
  92625. if (mesh.parent) {
  92626. return false;
  92627. }
  92628. return true;
  92629. };
  92630. return _this;
  92631. }
  92632. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92633. /**
  92634. * Gets or sets a boolean which defines if optimization octree has to be updated
  92635. */
  92636. get: function () {
  92637. return MergeMeshesOptimization._UpdateSelectionTree;
  92638. },
  92639. /**
  92640. * Gets or sets a boolean which defines if optimization octree has to be updated
  92641. */
  92642. set: function (value) {
  92643. MergeMeshesOptimization._UpdateSelectionTree = value;
  92644. },
  92645. enumerable: true,
  92646. configurable: true
  92647. });
  92648. /**
  92649. * Gets a string describing the action executed by the current optimization
  92650. * @return description string
  92651. */
  92652. MergeMeshesOptimization.prototype.getDescription = function () {
  92653. return "Merging similar meshes together";
  92654. };
  92655. /**
  92656. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92657. * @param scene defines the current scene where to apply this optimization
  92658. * @param optimizer defines the current optimizer
  92659. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  92660. * @returns true if everything that can be done was applied
  92661. */
  92662. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  92663. var globalPool = scene.meshes.slice(0);
  92664. var globalLength = globalPool.length;
  92665. for (var index = 0; index < globalLength; index++) {
  92666. var currentPool = new Array();
  92667. var current = globalPool[index];
  92668. // Checks
  92669. if (!this._canBeMerged(current)) {
  92670. continue;
  92671. }
  92672. currentPool.push(current);
  92673. // Find compatible meshes
  92674. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  92675. var otherMesh = globalPool[subIndex];
  92676. if (!this._canBeMerged(otherMesh)) {
  92677. continue;
  92678. }
  92679. if (otherMesh.material !== current.material) {
  92680. continue;
  92681. }
  92682. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92683. continue;
  92684. }
  92685. currentPool.push(otherMesh);
  92686. globalLength--;
  92687. globalPool.splice(subIndex, 1);
  92688. subIndex--;
  92689. }
  92690. if (currentPool.length < 2) {
  92691. continue;
  92692. }
  92693. // Merge meshes
  92694. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92695. }
  92696. if (updateSelectionTree != undefined) {
  92697. if (updateSelectionTree) {
  92698. scene.createOrUpdateSelectionOctree();
  92699. }
  92700. }
  92701. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92702. scene.createOrUpdateSelectionOctree();
  92703. }
  92704. return true;
  92705. };
  92706. ;
  92707. MergeMeshesOptimization._UpdateSelectionTree = false;
  92708. return MergeMeshesOptimization;
  92709. }(SceneOptimization));
  92710. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92711. /**
  92712. * Defines a list of options used by SceneOptimizer
  92713. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92714. */
  92715. var SceneOptimizerOptions = /** @class */ (function () {
  92716. /**
  92717. * Creates a new list of options used by SceneOptimizer
  92718. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92719. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92720. */
  92721. function SceneOptimizerOptions(
  92722. /**
  92723. * Defines the target frame rate to reach (60 by default)
  92724. */
  92725. targetFrameRate,
  92726. /**
  92727. * Defines the interval between two checkes (2000ms by default)
  92728. */
  92729. trackerDuration) {
  92730. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92731. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92732. this.targetFrameRate = targetFrameRate;
  92733. this.trackerDuration = trackerDuration;
  92734. /**
  92735. * Gets the list of optimizations to apply
  92736. */
  92737. this.optimizations = new Array();
  92738. }
  92739. /**
  92740. * Add a new optimization
  92741. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92742. * @returns the current SceneOptimizerOptions
  92743. */
  92744. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92745. this.optimizations.push(optimization);
  92746. return this;
  92747. };
  92748. /**
  92749. * Add a new custom optimization
  92750. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92751. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92752. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92753. * @returns the current SceneOptimizerOptions
  92754. */
  92755. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92756. if (priority === void 0) { priority = 0; }
  92757. var optimization = new CustomOptimization(priority);
  92758. optimization.onApply = onApply;
  92759. optimization.onGetDescription = onGetDescription;
  92760. this.optimizations.push(optimization);
  92761. return this;
  92762. };
  92763. /**
  92764. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92765. * @param targetFrameRate defines the target frame rate (60 by default)
  92766. * @returns a SceneOptimizerOptions object
  92767. */
  92768. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92769. var result = new SceneOptimizerOptions(targetFrameRate);
  92770. var priority = 0;
  92771. result.addOptimization(new MergeMeshesOptimization(priority));
  92772. result.addOptimization(new ShadowsOptimization(priority));
  92773. result.addOptimization(new LensFlaresOptimization(priority));
  92774. // Next priority
  92775. priority++;
  92776. result.addOptimization(new PostProcessesOptimization(priority));
  92777. result.addOptimization(new ParticlesOptimization(priority));
  92778. // Next priority
  92779. priority++;
  92780. result.addOptimization(new TextureOptimization(priority, 1024));
  92781. return result;
  92782. };
  92783. /**
  92784. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92785. * @param targetFrameRate defines the target frame rate (60 by default)
  92786. * @returns a SceneOptimizerOptions object
  92787. */
  92788. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92789. var result = new SceneOptimizerOptions(targetFrameRate);
  92790. var priority = 0;
  92791. result.addOptimization(new MergeMeshesOptimization(priority));
  92792. result.addOptimization(new ShadowsOptimization(priority));
  92793. result.addOptimization(new LensFlaresOptimization(priority));
  92794. // Next priority
  92795. priority++;
  92796. result.addOptimization(new PostProcessesOptimization(priority));
  92797. result.addOptimization(new ParticlesOptimization(priority));
  92798. // Next priority
  92799. priority++;
  92800. result.addOptimization(new TextureOptimization(priority, 512));
  92801. // Next priority
  92802. priority++;
  92803. result.addOptimization(new RenderTargetsOptimization(priority));
  92804. // Next priority
  92805. priority++;
  92806. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92807. return result;
  92808. };
  92809. /**
  92810. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92811. * @param targetFrameRate defines the target frame rate (60 by default)
  92812. * @returns a SceneOptimizerOptions object
  92813. */
  92814. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92815. var result = new SceneOptimizerOptions(targetFrameRate);
  92816. var priority = 0;
  92817. result.addOptimization(new MergeMeshesOptimization(priority));
  92818. result.addOptimization(new ShadowsOptimization(priority));
  92819. result.addOptimization(new LensFlaresOptimization(priority));
  92820. // Next priority
  92821. priority++;
  92822. result.addOptimization(new PostProcessesOptimization(priority));
  92823. result.addOptimization(new ParticlesOptimization(priority));
  92824. // Next priority
  92825. priority++;
  92826. result.addOptimization(new TextureOptimization(priority, 256));
  92827. // Next priority
  92828. priority++;
  92829. result.addOptimization(new RenderTargetsOptimization(priority));
  92830. // Next priority
  92831. priority++;
  92832. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92833. return result;
  92834. };
  92835. return SceneOptimizerOptions;
  92836. }());
  92837. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92838. /**
  92839. * Class used to run optimizations in order to reach a target frame rate
  92840. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92841. */
  92842. var SceneOptimizer = /** @class */ (function () {
  92843. /**
  92844. * Creates a new SceneOptimizer
  92845. * @param scene defines the scene to work on
  92846. * @param options defines the options to use with the SceneOptimizer
  92847. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  92848. * @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)
  92849. */
  92850. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  92851. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  92852. if (improvementMode === void 0) { improvementMode = false; }
  92853. var _this = this;
  92854. this._isRunning = false;
  92855. this._currentPriorityLevel = 0;
  92856. this._targetFrameRate = 60;
  92857. this._trackerDuration = 2000;
  92858. this._currentFrameRate = 0;
  92859. this._improvementMode = false;
  92860. /**
  92861. * Defines an observable called when the optimizer reaches the target frame rate
  92862. */
  92863. this.onSuccessObservable = new BABYLON.Observable();
  92864. /**
  92865. * Defines an observable called when the optimizer enables an optimization
  92866. */
  92867. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  92868. /**
  92869. * Defines an observable called when the optimizer is not able to reach the target frame rate
  92870. */
  92871. this.onFailureObservable = new BABYLON.Observable();
  92872. if (!options) {
  92873. this._options = new SceneOptimizerOptions();
  92874. }
  92875. else {
  92876. this._options = options;
  92877. }
  92878. if (this._options.targetFrameRate) {
  92879. this._targetFrameRate = this._options.targetFrameRate;
  92880. }
  92881. if (this._options.trackerDuration) {
  92882. this._trackerDuration = this._options.trackerDuration;
  92883. }
  92884. if (autoGeneratePriorities) {
  92885. var priority = 0;
  92886. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  92887. var optim = _a[_i];
  92888. optim.priority = priority++;
  92889. }
  92890. }
  92891. this._improvementMode = improvementMode;
  92892. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92893. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  92894. _this._sceneDisposeObserver = null;
  92895. _this.dispose();
  92896. });
  92897. }
  92898. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  92899. /**
  92900. * Gets a boolean indicating if the optimizer is in improvement mode
  92901. */
  92902. get: function () {
  92903. return this._improvementMode;
  92904. },
  92905. enumerable: true,
  92906. configurable: true
  92907. });
  92908. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  92909. /**
  92910. * Gets the current priority level (0 at start)
  92911. */
  92912. get: function () {
  92913. return this._currentPriorityLevel;
  92914. },
  92915. enumerable: true,
  92916. configurable: true
  92917. });
  92918. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  92919. /**
  92920. * Gets the current frame rate checked by the SceneOptimizer
  92921. */
  92922. get: function () {
  92923. return this._currentFrameRate;
  92924. },
  92925. enumerable: true,
  92926. configurable: true
  92927. });
  92928. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  92929. /**
  92930. * Gets or sets the current target frame rate (60 by default)
  92931. */
  92932. get: function () {
  92933. return this._targetFrameRate;
  92934. },
  92935. /**
  92936. * Gets or sets the current target frame rate (60 by default)
  92937. */
  92938. set: function (value) {
  92939. this._targetFrameRate = value;
  92940. },
  92941. enumerable: true,
  92942. configurable: true
  92943. });
  92944. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  92945. /**
  92946. * Gets or sets the current interval between two checks (every 2000ms by default)
  92947. */
  92948. get: function () {
  92949. return this._trackerDuration;
  92950. },
  92951. /**
  92952. * Gets or sets the current interval between two checks (every 2000ms by default)
  92953. */
  92954. set: function (value) {
  92955. this._trackerDuration = value;
  92956. },
  92957. enumerable: true,
  92958. configurable: true
  92959. });
  92960. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  92961. /**
  92962. * Gets the list of active optimizations
  92963. */
  92964. get: function () {
  92965. return this._options.optimizations;
  92966. },
  92967. enumerable: true,
  92968. configurable: true
  92969. });
  92970. /**
  92971. * Stops the current optimizer
  92972. */
  92973. SceneOptimizer.prototype.stop = function () {
  92974. this._isRunning = false;
  92975. };
  92976. /**
  92977. * Reset the optimizer to initial step (current priority level = 0)
  92978. */
  92979. SceneOptimizer.prototype.reset = function () {
  92980. this._currentPriorityLevel = 0;
  92981. };
  92982. /**
  92983. * Start the optimizer. By default it will try to reach a specific framerate
  92984. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  92985. */
  92986. SceneOptimizer.prototype.start = function () {
  92987. var _this = this;
  92988. if (this._isRunning) {
  92989. return;
  92990. }
  92991. this._isRunning = true;
  92992. // Let's wait for the scene to be ready before running our check
  92993. this._scene.executeWhenReady(function () {
  92994. setTimeout(function () {
  92995. _this._checkCurrentState();
  92996. }, _this._trackerDuration);
  92997. });
  92998. };
  92999. SceneOptimizer.prototype._checkCurrentState = function () {
  93000. var _this = this;
  93001. if (!this._isRunning) {
  93002. return;
  93003. }
  93004. var scene = this._scene;
  93005. var options = this._options;
  93006. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  93007. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  93008. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  93009. this._isRunning = false;
  93010. this.onSuccessObservable.notifyObservers(this);
  93011. return;
  93012. }
  93013. // Apply current level of optimizations
  93014. var allDone = true;
  93015. var noOptimizationApplied = true;
  93016. for (var index = 0; index < options.optimizations.length; index++) {
  93017. var optimization = options.optimizations[index];
  93018. if (optimization.priority === this._currentPriorityLevel) {
  93019. noOptimizationApplied = false;
  93020. allDone = allDone && optimization.apply(scene, this);
  93021. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  93022. }
  93023. }
  93024. // If no optimization was applied, this is a failure :(
  93025. if (noOptimizationApplied) {
  93026. this._isRunning = false;
  93027. this.onFailureObservable.notifyObservers(this);
  93028. return;
  93029. }
  93030. // If all optimizations were done, move to next level
  93031. if (allDone) {
  93032. this._currentPriorityLevel++;
  93033. }
  93034. // Let's the system running for a specific amount of time before checking FPS
  93035. scene.executeWhenReady(function () {
  93036. setTimeout(function () {
  93037. _this._checkCurrentState();
  93038. }, _this._trackerDuration);
  93039. });
  93040. };
  93041. /**
  93042. * Release all resources
  93043. */
  93044. SceneOptimizer.prototype.dispose = function () {
  93045. this.stop();
  93046. this.onSuccessObservable.clear();
  93047. this.onFailureObservable.clear();
  93048. this.onNewOptimizationAppliedObservable.clear();
  93049. if (this._sceneDisposeObserver) {
  93050. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93051. }
  93052. };
  93053. /**
  93054. * Helper function to create a SceneOptimizer with one single line of code
  93055. * @param scene defines the scene to work on
  93056. * @param options defines the options to use with the SceneOptimizer
  93057. * @param onSuccess defines a callback to call on success
  93058. * @param onFailure defines a callback to call on failure
  93059. * @returns the new SceneOptimizer object
  93060. */
  93061. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93062. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93063. if (onSuccess) {
  93064. optimizer.onSuccessObservable.add(function () {
  93065. onSuccess();
  93066. });
  93067. }
  93068. if (onFailure) {
  93069. optimizer.onFailureObservable.add(function () {
  93070. onFailure();
  93071. });
  93072. }
  93073. optimizer.start();
  93074. return optimizer;
  93075. };
  93076. return SceneOptimizer;
  93077. }());
  93078. BABYLON.SceneOptimizer = SceneOptimizer;
  93079. })(BABYLON || (BABYLON = {}));
  93080. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93081. var BABYLON;
  93082. (function (BABYLON) {
  93083. var OutlineRenderer = /** @class */ (function () {
  93084. function OutlineRenderer(scene) {
  93085. this.zOffset = 1;
  93086. this._scene = scene;
  93087. }
  93088. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93089. var _this = this;
  93090. if (useOverlay === void 0) { useOverlay = false; }
  93091. var scene = this._scene;
  93092. var engine = this._scene.getEngine();
  93093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93094. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93095. return;
  93096. }
  93097. var mesh = subMesh.getRenderingMesh();
  93098. var material = subMesh.getMaterial();
  93099. if (!material || !scene.activeCamera) {
  93100. return;
  93101. }
  93102. engine.enableEffect(this._effect);
  93103. // Logarithmic depth
  93104. if (material.useLogarithmicDepth) {
  93105. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93106. }
  93107. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93108. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93109. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93110. // Bones
  93111. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93112. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93113. }
  93114. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93115. // Alpha test
  93116. if (material && material.needAlphaTesting()) {
  93117. var alphaTexture = material.getAlphaTestTexture();
  93118. if (alphaTexture) {
  93119. this._effect.setTexture("diffuseSampler", alphaTexture);
  93120. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93121. }
  93122. }
  93123. engine.setZOffset(-this.zOffset);
  93124. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93125. engine.setZOffset(0);
  93126. };
  93127. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93128. var defines = [];
  93129. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93130. var mesh = subMesh.getMesh();
  93131. var material = subMesh.getMaterial();
  93132. if (material) {
  93133. // Alpha test
  93134. if (material.needAlphaTesting()) {
  93135. defines.push("#define ALPHATEST");
  93136. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93137. attribs.push(BABYLON.VertexBuffer.UVKind);
  93138. defines.push("#define UV1");
  93139. }
  93140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93141. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93142. defines.push("#define UV2");
  93143. }
  93144. }
  93145. //Logarithmic depth
  93146. if (material.useLogarithmicDepth) {
  93147. defines.push("#define LOGARITHMICDEPTH");
  93148. }
  93149. }
  93150. // Bones
  93151. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93152. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93153. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93154. if (mesh.numBoneInfluencers > 4) {
  93155. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93156. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93157. }
  93158. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93159. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93160. }
  93161. else {
  93162. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93163. }
  93164. // Instances
  93165. if (useInstances) {
  93166. defines.push("#define INSTANCES");
  93167. attribs.push("world0");
  93168. attribs.push("world1");
  93169. attribs.push("world2");
  93170. attribs.push("world3");
  93171. }
  93172. // Get correct effect
  93173. var join = defines.join("\n");
  93174. if (this._cachedDefines !== join) {
  93175. this._cachedDefines = join;
  93176. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93177. }
  93178. return this._effect.isReady();
  93179. };
  93180. return OutlineRenderer;
  93181. }());
  93182. BABYLON.OutlineRenderer = OutlineRenderer;
  93183. })(BABYLON || (BABYLON = {}));
  93184. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93185. var BABYLON;
  93186. (function (BABYLON) {
  93187. var FaceAdjacencies = /** @class */ (function () {
  93188. function FaceAdjacencies() {
  93189. this.edges = new Array();
  93190. this.edgesConnectedCount = 0;
  93191. }
  93192. return FaceAdjacencies;
  93193. }());
  93194. var EdgesRenderer = /** @class */ (function () {
  93195. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93196. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93197. if (epsilon === void 0) { epsilon = 0.95; }
  93198. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93199. this.edgesWidthScalerForOrthographic = 1000.0;
  93200. this.edgesWidthScalerForPerspective = 50.0;
  93201. this._linesPositions = new Array();
  93202. this._linesNormals = new Array();
  93203. this._linesIndices = new Array();
  93204. this._buffers = {};
  93205. this._checkVerticesInsteadOfIndices = false;
  93206. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93207. this.isEnabled = true;
  93208. this._source = source;
  93209. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93210. this._epsilon = epsilon;
  93211. this._prepareRessources();
  93212. this._generateEdgesLines();
  93213. }
  93214. EdgesRenderer.prototype._prepareRessources = function () {
  93215. if (this._lineShader) {
  93216. return;
  93217. }
  93218. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93219. attributes: ["position", "normal"],
  93220. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93221. });
  93222. this._lineShader.disableDepthWrite = true;
  93223. this._lineShader.backFaceCulling = false;
  93224. };
  93225. EdgesRenderer.prototype._rebuild = function () {
  93226. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93227. if (buffer) {
  93228. buffer._rebuild();
  93229. }
  93230. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93231. if (buffer) {
  93232. buffer._rebuild();
  93233. }
  93234. var scene = this._source.getScene();
  93235. var engine = scene.getEngine();
  93236. this._ib = engine.createIndexBuffer(this._linesIndices);
  93237. };
  93238. EdgesRenderer.prototype.dispose = function () {
  93239. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93240. if (buffer) {
  93241. buffer.dispose();
  93242. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93243. }
  93244. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93245. if (buffer) {
  93246. buffer.dispose();
  93247. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93248. }
  93249. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93250. this._lineShader.dispose();
  93251. };
  93252. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93253. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93254. return 0;
  93255. }
  93256. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93257. return 1;
  93258. }
  93259. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93260. return 2;
  93261. }
  93262. return -1;
  93263. };
  93264. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93265. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93266. return 0;
  93267. }
  93268. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93269. return 1;
  93270. }
  93271. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93272. return 2;
  93273. }
  93274. return -1;
  93275. };
  93276. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93277. var needToCreateLine;
  93278. if (edge === undefined) {
  93279. needToCreateLine = true;
  93280. }
  93281. else {
  93282. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93283. needToCreateLine = dotProduct < this._epsilon;
  93284. }
  93285. if (needToCreateLine) {
  93286. var offset = this._linesPositions.length / 3;
  93287. var normal = p0.subtract(p1);
  93288. normal.normalize();
  93289. // Positions
  93290. this._linesPositions.push(p0.x);
  93291. this._linesPositions.push(p0.y);
  93292. this._linesPositions.push(p0.z);
  93293. this._linesPositions.push(p0.x);
  93294. this._linesPositions.push(p0.y);
  93295. this._linesPositions.push(p0.z);
  93296. this._linesPositions.push(p1.x);
  93297. this._linesPositions.push(p1.y);
  93298. this._linesPositions.push(p1.z);
  93299. this._linesPositions.push(p1.x);
  93300. this._linesPositions.push(p1.y);
  93301. this._linesPositions.push(p1.z);
  93302. // Normals
  93303. this._linesNormals.push(p1.x);
  93304. this._linesNormals.push(p1.y);
  93305. this._linesNormals.push(p1.z);
  93306. this._linesNormals.push(-1);
  93307. this._linesNormals.push(p1.x);
  93308. this._linesNormals.push(p1.y);
  93309. this._linesNormals.push(p1.z);
  93310. this._linesNormals.push(1);
  93311. this._linesNormals.push(p0.x);
  93312. this._linesNormals.push(p0.y);
  93313. this._linesNormals.push(p0.z);
  93314. this._linesNormals.push(-1);
  93315. this._linesNormals.push(p0.x);
  93316. this._linesNormals.push(p0.y);
  93317. this._linesNormals.push(p0.z);
  93318. this._linesNormals.push(1);
  93319. // Indices
  93320. this._linesIndices.push(offset);
  93321. this._linesIndices.push(offset + 1);
  93322. this._linesIndices.push(offset + 2);
  93323. this._linesIndices.push(offset);
  93324. this._linesIndices.push(offset + 2);
  93325. this._linesIndices.push(offset + 3);
  93326. }
  93327. };
  93328. EdgesRenderer.prototype._generateEdgesLines = function () {
  93329. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93330. var indices = this._source.getIndices();
  93331. if (!indices || !positions) {
  93332. return;
  93333. }
  93334. // First let's find adjacencies
  93335. var adjacencies = new Array();
  93336. var faceNormals = new Array();
  93337. var index;
  93338. var faceAdjacencies;
  93339. // Prepare faces
  93340. for (index = 0; index < indices.length; index += 3) {
  93341. faceAdjacencies = new FaceAdjacencies();
  93342. var p0Index = indices[index];
  93343. var p1Index = indices[index + 1];
  93344. var p2Index = indices[index + 2];
  93345. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93346. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93347. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93348. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93349. faceNormal.normalize();
  93350. faceNormals.push(faceNormal);
  93351. adjacencies.push(faceAdjacencies);
  93352. }
  93353. // Scan
  93354. for (index = 0; index < adjacencies.length; index++) {
  93355. faceAdjacencies = adjacencies[index];
  93356. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93357. var otherFaceAdjacencies = adjacencies[otherIndex];
  93358. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93359. break;
  93360. }
  93361. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93362. continue;
  93363. }
  93364. var otherP0 = indices[otherIndex * 3];
  93365. var otherP1 = indices[otherIndex * 3 + 1];
  93366. var otherP2 = indices[otherIndex * 3 + 2];
  93367. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93368. var otherEdgeIndex = 0;
  93369. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93370. continue;
  93371. }
  93372. switch (edgeIndex) {
  93373. case 0:
  93374. if (this._checkVerticesInsteadOfIndices) {
  93375. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93376. }
  93377. else {
  93378. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93379. }
  93380. break;
  93381. case 1:
  93382. if (this._checkVerticesInsteadOfIndices) {
  93383. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93384. }
  93385. else {
  93386. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93387. }
  93388. break;
  93389. case 2:
  93390. if (this._checkVerticesInsteadOfIndices) {
  93391. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93392. }
  93393. else {
  93394. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93395. }
  93396. break;
  93397. }
  93398. if (otherEdgeIndex === -1) {
  93399. continue;
  93400. }
  93401. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93402. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93403. faceAdjacencies.edgesConnectedCount++;
  93404. otherFaceAdjacencies.edgesConnectedCount++;
  93405. if (faceAdjacencies.edgesConnectedCount === 3) {
  93406. break;
  93407. }
  93408. }
  93409. }
  93410. }
  93411. // Create lines
  93412. for (index = 0; index < adjacencies.length; index++) {
  93413. // 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
  93414. var current = adjacencies[index];
  93415. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93416. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93417. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93418. }
  93419. // Merge into a single mesh
  93420. var engine = this._source.getScene().getEngine();
  93421. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93422. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93423. this._ib = engine.createIndexBuffer(this._linesIndices);
  93424. this._indicesCount = this._linesIndices.length;
  93425. };
  93426. EdgesRenderer.prototype.render = function () {
  93427. var scene = this._source.getScene();
  93428. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93429. return;
  93430. }
  93431. var engine = scene.getEngine();
  93432. this._lineShader._preBind();
  93433. // VBOs
  93434. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93435. scene.resetCachedMaterial();
  93436. this._lineShader.setColor4("color", this._source.edgesColor);
  93437. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93438. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93439. }
  93440. else {
  93441. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93442. }
  93443. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93444. this._lineShader.bind(this._source.getWorldMatrix());
  93445. // Draw order
  93446. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93447. this._lineShader.unbind();
  93448. engine.setDepthWrite(true);
  93449. };
  93450. return EdgesRenderer;
  93451. }());
  93452. BABYLON.EdgesRenderer = EdgesRenderer;
  93453. })(BABYLON || (BABYLON = {}));
  93454. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93455. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93456. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93457. s = arguments[i];
  93458. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93459. t[p] = s[p];
  93460. }
  93461. return t;
  93462. };
  93463. var BABYLON;
  93464. (function (BABYLON) {
  93465. /**
  93466. * The effect layer Helps adding post process effect blended with the main pass.
  93467. *
  93468. * This can be for instance use to generate glow or higlight effects on the scene.
  93469. *
  93470. * The effect layer class can not be used directly and is intented to inherited from to be
  93471. * customized per effects.
  93472. */
  93473. var EffectLayer = /** @class */ (function () {
  93474. /**
  93475. * Instantiates a new effect Layer and references it in the scene.
  93476. * @param name The name of the layer
  93477. * @param scene The scene to use the layer in
  93478. */
  93479. function EffectLayer(
  93480. /** The Friendly of the effect in the scene */
  93481. name, scene) {
  93482. this._vertexBuffers = {};
  93483. this._maxSize = 0;
  93484. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93485. this._shouldRender = true;
  93486. this._postProcesses = [];
  93487. this._textures = [];
  93488. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93489. /**
  93490. * The clear color of the texture used to generate the glow map.
  93491. */
  93492. this.neutralColor = new BABYLON.Color4();
  93493. /**
  93494. * Specifies wether the highlight layer is enabled or not.
  93495. */
  93496. this.isEnabled = true;
  93497. /**
  93498. * An event triggered when the effect layer has been disposed.
  93499. */
  93500. this.onDisposeObservable = new BABYLON.Observable();
  93501. /**
  93502. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93503. */
  93504. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93505. /**
  93506. * An event triggered when the generated texture is being merged in the scene.
  93507. */
  93508. this.onBeforeComposeObservable = new BABYLON.Observable();
  93509. /**
  93510. * An event triggered when the generated texture has been merged in the scene.
  93511. */
  93512. this.onAfterComposeObservable = new BABYLON.Observable();
  93513. /**
  93514. * An event triggered when the efffect layer changes its size.
  93515. */
  93516. this.onSizeChangedObservable = new BABYLON.Observable();
  93517. this.name = name;
  93518. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93519. this._engine = scene.getEngine();
  93520. this._maxSize = this._engine.getCaps().maxTextureSize;
  93521. this._scene.effectLayers.push(this);
  93522. // Generate Buffers
  93523. this._generateIndexBuffer();
  93524. this._genrateVertexBuffer();
  93525. }
  93526. Object.defineProperty(EffectLayer.prototype, "camera", {
  93527. /**
  93528. * Gets the camera attached to the layer.
  93529. */
  93530. get: function () {
  93531. return this._effectLayerOptions.camera;
  93532. },
  93533. enumerable: true,
  93534. configurable: true
  93535. });
  93536. /**
  93537. * Initializes the effect layer with the required options.
  93538. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93539. */
  93540. EffectLayer.prototype._init = function (options) {
  93541. // Adapt options
  93542. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93543. this._setMainTextureSize();
  93544. this._createMainTexture();
  93545. this._createTextureAndPostProcesses();
  93546. this._mergeEffect = this._createMergeEffect();
  93547. };
  93548. /**
  93549. * Generates the index buffer of the full screen quad blending to the main canvas.
  93550. */
  93551. EffectLayer.prototype._generateIndexBuffer = function () {
  93552. // Indices
  93553. var indices = [];
  93554. indices.push(0);
  93555. indices.push(1);
  93556. indices.push(2);
  93557. indices.push(0);
  93558. indices.push(2);
  93559. indices.push(3);
  93560. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93561. };
  93562. /**
  93563. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93564. */
  93565. EffectLayer.prototype._genrateVertexBuffer = function () {
  93566. // VBO
  93567. var vertices = [];
  93568. vertices.push(1, 1);
  93569. vertices.push(-1, 1);
  93570. vertices.push(-1, -1);
  93571. vertices.push(1, -1);
  93572. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93573. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93574. };
  93575. /**
  93576. * Sets the main texture desired size which is the closest power of two
  93577. * of the engine canvas size.
  93578. */
  93579. EffectLayer.prototype._setMainTextureSize = function () {
  93580. if (this._effectLayerOptions.mainTextureFixedSize) {
  93581. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93582. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93583. }
  93584. else {
  93585. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93586. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93587. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93588. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93589. }
  93590. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93591. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93592. };
  93593. /**
  93594. * Creates the main texture for the effect layer.
  93595. */
  93596. EffectLayer.prototype._createMainTexture = function () {
  93597. var _this = this;
  93598. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93599. width: this._mainTextureDesiredSize.width,
  93600. height: this._mainTextureDesiredSize.height
  93601. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93602. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93603. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93604. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93605. this._mainTexture.anisotropicFilteringLevel = 1;
  93606. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93607. this._mainTexture.renderParticles = false;
  93608. this._mainTexture.renderList = null;
  93609. this._mainTexture.ignoreCameraViewport = true;
  93610. // Custom render function
  93611. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93612. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93613. var index;
  93614. var engine = _this._scene.getEngine();
  93615. if (depthOnlySubMeshes.length) {
  93616. engine.setColorWrite(false);
  93617. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93618. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93619. }
  93620. engine.setColorWrite(true);
  93621. }
  93622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93623. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93624. }
  93625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93626. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93627. }
  93628. for (index = 0; index < transparentSubMeshes.length; index++) {
  93629. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93630. }
  93631. };
  93632. this._mainTexture.onClearObservable.add(function (engine) {
  93633. engine.clear(_this.neutralColor, true, true, true);
  93634. });
  93635. };
  93636. /**
  93637. * Checks for the readiness of the element composing the layer.
  93638. * @param subMesh the mesh to check for
  93639. * @param useInstances specify wether or not to use instances to render the mesh
  93640. * @param emissiveTexture the associated emissive texture used to generate the glow
  93641. * @return true if ready otherwise, false
  93642. */
  93643. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93644. var material = subMesh.getMaterial();
  93645. if (!material) {
  93646. return false;
  93647. }
  93648. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  93649. return false;
  93650. }
  93651. var defines = [];
  93652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93653. var mesh = subMesh.getMesh();
  93654. var uv1 = false;
  93655. var uv2 = false;
  93656. // Alpha test
  93657. if (material && material.needAlphaTesting()) {
  93658. var alphaTexture = material.getAlphaTestTexture();
  93659. if (alphaTexture) {
  93660. defines.push("#define ALPHATEST");
  93661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93662. alphaTexture.coordinatesIndex === 1) {
  93663. defines.push("#define DIFFUSEUV2");
  93664. uv2 = true;
  93665. }
  93666. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93667. defines.push("#define DIFFUSEUV1");
  93668. uv1 = true;
  93669. }
  93670. }
  93671. }
  93672. // Emissive
  93673. if (emissiveTexture) {
  93674. defines.push("#define EMISSIVE");
  93675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93676. emissiveTexture.coordinatesIndex === 1) {
  93677. defines.push("#define EMISSIVEUV2");
  93678. uv2 = true;
  93679. }
  93680. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93681. defines.push("#define EMISSIVEUV1");
  93682. uv1 = true;
  93683. }
  93684. }
  93685. if (uv1) {
  93686. attribs.push(BABYLON.VertexBuffer.UVKind);
  93687. defines.push("#define UV1");
  93688. }
  93689. if (uv2) {
  93690. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93691. defines.push("#define UV2");
  93692. }
  93693. // Bones
  93694. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93695. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93696. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93697. if (mesh.numBoneInfluencers > 4) {
  93698. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93699. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93700. }
  93701. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93702. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93703. }
  93704. else {
  93705. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93706. }
  93707. // Morph targets
  93708. var manager = mesh.morphTargetManager;
  93709. var morphInfluencers = 0;
  93710. if (manager) {
  93711. if (manager.numInfluencers > 0) {
  93712. defines.push("#define MORPHTARGETS");
  93713. morphInfluencers = manager.numInfluencers;
  93714. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93715. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93716. }
  93717. }
  93718. // Instances
  93719. if (useInstances) {
  93720. defines.push("#define INSTANCES");
  93721. attribs.push("world0");
  93722. attribs.push("world1");
  93723. attribs.push("world2");
  93724. attribs.push("world3");
  93725. }
  93726. // Get correct effect
  93727. var join = defines.join("\n");
  93728. if (this._cachedDefines !== join) {
  93729. this._cachedDefines = join;
  93730. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93731. }
  93732. return this._effectLayerMapGenerationEffect.isReady();
  93733. };
  93734. /**
  93735. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93736. */
  93737. EffectLayer.prototype.render = function () {
  93738. var currentEffect = this._mergeEffect;
  93739. // Check
  93740. if (!currentEffect.isReady())
  93741. return;
  93742. for (var i = 0; i < this._postProcesses.length; i++) {
  93743. if (!this._postProcesses[i].isReady()) {
  93744. return;
  93745. }
  93746. }
  93747. var engine = this._scene.getEngine();
  93748. this.onBeforeComposeObservable.notifyObservers(this);
  93749. // Render
  93750. engine.enableEffect(currentEffect);
  93751. engine.setState(false);
  93752. // VBOs
  93753. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93754. // Cache
  93755. var previousAlphaMode = engine.getAlphaMode();
  93756. // Go Blend.
  93757. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93758. // Blends the map on the main canvas.
  93759. this._internalRender(currentEffect);
  93760. // Restore Alpha
  93761. engine.setAlphaMode(previousAlphaMode);
  93762. this.onAfterComposeObservable.notifyObservers(this);
  93763. // Handle size changes.
  93764. var size = this._mainTexture.getSize();
  93765. this._setMainTextureSize();
  93766. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93767. // Recreate RTT and post processes on size change.
  93768. this.onSizeChangedObservable.notifyObservers(this);
  93769. this._disposeTextureAndPostProcesses();
  93770. this._createMainTexture();
  93771. this._createTextureAndPostProcesses();
  93772. }
  93773. };
  93774. /**
  93775. * Determine if a given mesh will be used in the current effect.
  93776. * @param mesh mesh to test
  93777. * @returns true if the mesh will be used
  93778. */
  93779. EffectLayer.prototype.hasMesh = function (mesh) {
  93780. return true;
  93781. };
  93782. /**
  93783. * Returns true if the layer contains information to display, otherwise false.
  93784. * @returns true if the glow layer should be rendered
  93785. */
  93786. EffectLayer.prototype.shouldRender = function () {
  93787. return this.isEnabled && this._shouldRender;
  93788. };
  93789. /**
  93790. * Returns true if the mesh should render, otherwise false.
  93791. * @param mesh The mesh to render
  93792. * @returns true if it should render otherwise false
  93793. */
  93794. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93795. return true;
  93796. };
  93797. /**
  93798. * Returns true if the mesh should render, otherwise false.
  93799. * @param mesh The mesh to render
  93800. * @returns true if it should render otherwise false
  93801. */
  93802. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93803. return true;
  93804. };
  93805. /**
  93806. * Renders the submesh passed in parameter to the generation map.
  93807. */
  93808. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93809. var _this = this;
  93810. if (!this.shouldRender()) {
  93811. return;
  93812. }
  93813. var material = subMesh.getMaterial();
  93814. var mesh = subMesh.getRenderingMesh();
  93815. var scene = this._scene;
  93816. var engine = scene.getEngine();
  93817. if (!material) {
  93818. return;
  93819. }
  93820. // Do not block in blend mode.
  93821. if (material.needAlphaBlendingForMesh(mesh)) {
  93822. return;
  93823. }
  93824. // Culling
  93825. engine.setState(material.backFaceCulling);
  93826. // Managing instances
  93827. var batch = mesh._getInstancesRenderList(subMesh._id);
  93828. if (batch.mustReturn) {
  93829. return;
  93830. }
  93831. // Early Exit per mesh
  93832. if (!this._shouldRenderMesh(mesh)) {
  93833. return;
  93834. }
  93835. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93836. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93837. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93838. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93839. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93840. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93841. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93842. // Alpha test
  93843. if (material && material.needAlphaTesting()) {
  93844. var alphaTexture = material.getAlphaTestTexture();
  93845. if (alphaTexture) {
  93846. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  93847. var textureMatrix = alphaTexture.getTextureMatrix();
  93848. if (textureMatrix) {
  93849. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  93850. }
  93851. }
  93852. }
  93853. // Glow emissive only
  93854. if (this._emissiveTextureAndColor.texture) {
  93855. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  93856. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  93857. }
  93858. // Bones
  93859. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93860. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93861. }
  93862. // Morph targets
  93863. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  93864. // Draw
  93865. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  93866. }
  93867. else {
  93868. // Need to reset refresh rate of the shadowMap
  93869. this._mainTexture.resetRefreshCounter();
  93870. }
  93871. };
  93872. /**
  93873. * Rebuild the required buffers.
  93874. * @hidden Internal use only.
  93875. */
  93876. EffectLayer.prototype._rebuild = function () {
  93877. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93878. if (vb) {
  93879. vb._rebuild();
  93880. }
  93881. this._generateIndexBuffer();
  93882. };
  93883. /**
  93884. * Dispose only the render target textures and post process.
  93885. */
  93886. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  93887. this._mainTexture.dispose();
  93888. for (var i = 0; i < this._postProcesses.length; i++) {
  93889. if (this._postProcesses[i]) {
  93890. this._postProcesses[i].dispose();
  93891. }
  93892. }
  93893. this._postProcesses = [];
  93894. for (var i = 0; i < this._textures.length; i++) {
  93895. if (this._textures[i]) {
  93896. this._textures[i].dispose();
  93897. }
  93898. }
  93899. this._textures = [];
  93900. };
  93901. /**
  93902. * Dispose the highlight layer and free resources.
  93903. */
  93904. EffectLayer.prototype.dispose = function () {
  93905. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93906. if (vertexBuffer) {
  93907. vertexBuffer.dispose();
  93908. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93909. }
  93910. if (this._indexBuffer) {
  93911. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93912. this._indexBuffer = null;
  93913. }
  93914. // Clean textures and post processes
  93915. this._disposeTextureAndPostProcesses();
  93916. // Remove from scene
  93917. var index = this._scene.effectLayers.indexOf(this, 0);
  93918. if (index > -1) {
  93919. this._scene.effectLayers.splice(index, 1);
  93920. }
  93921. // Callback
  93922. this.onDisposeObservable.notifyObservers(this);
  93923. this.onDisposeObservable.clear();
  93924. this.onBeforeRenderMainTextureObservable.clear();
  93925. this.onBeforeComposeObservable.clear();
  93926. this.onAfterComposeObservable.clear();
  93927. this.onSizeChangedObservable.clear();
  93928. };
  93929. /**
  93930. * Gets the class name of the effect layer
  93931. * @returns the string with the class name of the effect layer
  93932. */
  93933. EffectLayer.prototype.getClassName = function () {
  93934. return "EffectLayer";
  93935. };
  93936. /**
  93937. * Creates an effect layer from parsed effect layer data
  93938. * @param parsedEffectLayer defines effect layer data
  93939. * @param scene defines the current scene
  93940. * @param rootUrl defines the root URL containing the effect layer information
  93941. * @returns a parsed effect Layer
  93942. */
  93943. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  93944. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  93945. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  93946. };
  93947. __decorate([
  93948. BABYLON.serialize()
  93949. ], EffectLayer.prototype, "name", void 0);
  93950. __decorate([
  93951. BABYLON.serializeAsColor4()
  93952. ], EffectLayer.prototype, "neutralColor", void 0);
  93953. __decorate([
  93954. BABYLON.serialize()
  93955. ], EffectLayer.prototype, "isEnabled", void 0);
  93956. __decorate([
  93957. BABYLON.serializeAsCameraReference()
  93958. ], EffectLayer.prototype, "camera", null);
  93959. return EffectLayer;
  93960. }());
  93961. BABYLON.EffectLayer = EffectLayer;
  93962. })(BABYLON || (BABYLON = {}));
  93963. //# sourceMappingURL=babylon.effectLayer.js.map
  93964. var BABYLON;
  93965. (function (BABYLON) {
  93966. /**
  93967. * Special Glow Blur post process only blurring the alpha channel
  93968. * It enforces keeping the most luminous color in the color channel.
  93969. */
  93970. var GlowBlurPostProcess = /** @class */ (function (_super) {
  93971. __extends(GlowBlurPostProcess, _super);
  93972. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  93973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  93974. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  93975. _this.direction = direction;
  93976. _this.kernel = kernel;
  93977. _this.onApplyObservable.add(function (effect) {
  93978. effect.setFloat2("screenSize", _this.width, _this.height);
  93979. effect.setVector2("direction", _this.direction);
  93980. effect.setFloat("blurWidth", _this.kernel);
  93981. });
  93982. return _this;
  93983. }
  93984. return GlowBlurPostProcess;
  93985. }(BABYLON.PostProcess));
  93986. /**
  93987. * The highlight layer Helps adding a glow effect around a mesh.
  93988. *
  93989. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93990. * glowy meshes to your scene.
  93991. *
  93992. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  93993. */
  93994. var HighlightLayer = /** @class */ (function (_super) {
  93995. __extends(HighlightLayer, _super);
  93996. /**
  93997. * Instantiates a new highlight Layer and references it to the scene..
  93998. * @param name The name of the layer
  93999. * @param scene The scene to use the layer in
  94000. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  94001. */
  94002. function HighlightLayer(name, scene, options) {
  94003. var _this = _super.call(this, name, scene) || this;
  94004. _this.name = name;
  94005. /**
  94006. * Specifies whether or not the inner glow is ACTIVE in the layer.
  94007. */
  94008. _this.innerGlow = true;
  94009. /**
  94010. * Specifies whether or not the outer glow is ACTIVE in the layer.
  94011. */
  94012. _this.outerGlow = true;
  94013. /**
  94014. * An event triggered when the highlight layer is being blurred.
  94015. */
  94016. _this.onBeforeBlurObservable = new BABYLON.Observable();
  94017. /**
  94018. * An event triggered when the highlight layer has been blurred.
  94019. */
  94020. _this.onAfterBlurObservable = new BABYLON.Observable();
  94021. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  94022. _this._meshes = {};
  94023. _this._excludedMeshes = {};
  94024. _this.neutralColor = HighlightLayer.NeutralColor;
  94025. // Warn on stencil
  94026. if (!_this._engine.isStencilEnable) {
  94027. 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 }");
  94028. }
  94029. // Adapt options
  94030. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  94031. // Initialize the layer
  94032. _this._init({
  94033. alphaBlendingMode: _this._options.alphaBlendingMode,
  94034. camera: _this._options.camera,
  94035. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94036. mainTextureRatio: _this._options.mainTextureRatio
  94037. });
  94038. // Do not render as long as no meshes have been added
  94039. _this._shouldRender = false;
  94040. return _this;
  94041. }
  94042. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94043. /**
  94044. * Gets the horizontal size of the blur.
  94045. */
  94046. get: function () {
  94047. return this._horizontalBlurPostprocess.kernel;
  94048. },
  94049. /**
  94050. * Specifies the horizontal size of the blur.
  94051. */
  94052. set: function (value) {
  94053. this._horizontalBlurPostprocess.kernel = value;
  94054. },
  94055. enumerable: true,
  94056. configurable: true
  94057. });
  94058. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94059. /**
  94060. * Gets the vertical size of the blur.
  94061. */
  94062. get: function () {
  94063. return this._verticalBlurPostprocess.kernel;
  94064. },
  94065. /**
  94066. * Specifies the vertical size of the blur.
  94067. */
  94068. set: function (value) {
  94069. this._verticalBlurPostprocess.kernel = value;
  94070. },
  94071. enumerable: true,
  94072. configurable: true
  94073. });
  94074. /**
  94075. * Get the effect name of the layer.
  94076. * @return The effect name
  94077. */
  94078. HighlightLayer.prototype.getEffectName = function () {
  94079. return HighlightLayer.EffectName;
  94080. };
  94081. /**
  94082. * Create the merge effect. This is the shader use to blit the information back
  94083. * to the main canvas at the end of the scene rendering.
  94084. */
  94085. HighlightLayer.prototype._createMergeEffect = function () {
  94086. // Effect
  94087. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94088. };
  94089. /**
  94090. * Creates the render target textures and post processes used in the highlight layer.
  94091. */
  94092. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94093. var _this = this;
  94094. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94095. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94096. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94097. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94098. var textureType = 0;
  94099. if (this._engine.getCaps().textureHalfFloatRender) {
  94100. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94101. }
  94102. else {
  94103. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94104. }
  94105. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94106. width: blurTextureWidth,
  94107. height: blurTextureHeight
  94108. }, this._scene, false, true, textureType);
  94109. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94110. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94111. this._blurTexture.anisotropicFilteringLevel = 16;
  94112. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94113. this._blurTexture.renderParticles = false;
  94114. this._blurTexture.ignoreCameraViewport = true;
  94115. this._textures = [this._blurTexture];
  94116. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94117. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94118. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94119. effect.setTexture("textureSampler", _this._mainTexture);
  94120. });
  94121. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94122. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94123. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94124. });
  94125. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94126. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94127. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94128. });
  94129. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94130. }
  94131. else {
  94132. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94133. width: blurTextureWidth,
  94134. height: blurTextureHeight
  94135. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94136. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94137. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94138. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94139. effect.setTexture("textureSampler", _this._mainTexture);
  94140. });
  94141. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94142. width: blurTextureWidth,
  94143. height: blurTextureHeight
  94144. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94145. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94146. }
  94147. this._mainTexture.onAfterUnbindObservable.add(function () {
  94148. _this.onBeforeBlurObservable.notifyObservers(_this);
  94149. var internalTexture = _this._blurTexture.getInternalTexture();
  94150. if (internalTexture) {
  94151. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94152. }
  94153. _this.onAfterBlurObservable.notifyObservers(_this);
  94154. });
  94155. // Prevent autoClear.
  94156. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94157. };
  94158. /**
  94159. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94160. */
  94161. HighlightLayer.prototype.needStencil = function () {
  94162. return true;
  94163. };
  94164. /**
  94165. * Checks for the readiness of the element composing the layer.
  94166. * @param subMesh the mesh to check for
  94167. * @param useInstances specify wether or not to use instances to render the mesh
  94168. * @param emissiveTexture the associated emissive texture used to generate the glow
  94169. * @return true if ready otherwise, false
  94170. */
  94171. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94172. var material = subMesh.getMaterial();
  94173. var mesh = subMesh.getRenderingMesh();
  94174. if (!material || !mesh || !this._meshes) {
  94175. return false;
  94176. }
  94177. var emissiveTexture = null;
  94178. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94179. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94180. emissiveTexture = material.emissiveTexture;
  94181. }
  94182. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94183. };
  94184. /**
  94185. * Implementation specific of rendering the generating effect on the main canvas.
  94186. * @param effect The effect used to render through
  94187. */
  94188. HighlightLayer.prototype._internalRender = function (effect) {
  94189. // Texture
  94190. effect.setTexture("textureSampler", this._blurTexture);
  94191. // Cache
  94192. var engine = this._engine;
  94193. var previousStencilBuffer = engine.getStencilBuffer();
  94194. var previousStencilFunction = engine.getStencilFunction();
  94195. var previousStencilMask = engine.getStencilMask();
  94196. var previousStencilOperationPass = engine.getStencilOperationPass();
  94197. var previousStencilOperationFail = engine.getStencilOperationFail();
  94198. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94199. var previousStencilReference = engine.getStencilFunctionReference();
  94200. // Stencil operations
  94201. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94202. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94203. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94204. // Draw order
  94205. engine.setStencilMask(0x00);
  94206. engine.setStencilBuffer(true);
  94207. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94208. // 2 passes inner outer
  94209. if (this.outerGlow) {
  94210. effect.setFloat("offset", 0);
  94211. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94212. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94213. }
  94214. if (this.innerGlow) {
  94215. effect.setFloat("offset", 1);
  94216. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94218. }
  94219. // Restore Cache
  94220. engine.setStencilFunction(previousStencilFunction);
  94221. engine.setStencilMask(previousStencilMask);
  94222. engine.setStencilBuffer(previousStencilBuffer);
  94223. engine.setStencilOperationPass(previousStencilOperationPass);
  94224. engine.setStencilOperationFail(previousStencilOperationFail);
  94225. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94226. engine.setStencilFunctionReference(previousStencilReference);
  94227. };
  94228. /**
  94229. * Returns true if the layer contains information to display, otherwise false.
  94230. */
  94231. HighlightLayer.prototype.shouldRender = function () {
  94232. if (_super.prototype.shouldRender.call(this)) {
  94233. return this._meshes ? true : false;
  94234. }
  94235. return false;
  94236. };
  94237. /**
  94238. * Returns true if the mesh should render, otherwise false.
  94239. * @param mesh The mesh to render
  94240. * @returns true if it should render otherwise false
  94241. */
  94242. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94243. // Excluded Mesh
  94244. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94245. return false;
  94246. }
  94247. ;
  94248. return true;
  94249. };
  94250. /**
  94251. * Sets the required values for both the emissive texture and and the main color.
  94252. */
  94253. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94254. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94255. if (highlightLayerMesh) {
  94256. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94257. }
  94258. else {
  94259. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94260. }
  94261. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94262. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94263. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94264. }
  94265. else {
  94266. this._emissiveTextureAndColor.texture = null;
  94267. }
  94268. };
  94269. /**
  94270. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94271. * @param mesh The mesh to exclude from the highlight layer
  94272. */
  94273. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94274. if (!this._excludedMeshes) {
  94275. return;
  94276. }
  94277. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94278. if (!meshExcluded) {
  94279. this._excludedMeshes[mesh.uniqueId] = {
  94280. mesh: mesh,
  94281. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94282. mesh.getEngine().setStencilBuffer(false);
  94283. }),
  94284. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94285. mesh.getEngine().setStencilBuffer(true);
  94286. }),
  94287. };
  94288. }
  94289. };
  94290. /**
  94291. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94292. * @param mesh The mesh to highlight
  94293. */
  94294. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94295. if (!this._excludedMeshes) {
  94296. return;
  94297. }
  94298. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94299. if (meshExcluded) {
  94300. if (meshExcluded.beforeRender) {
  94301. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94302. }
  94303. if (meshExcluded.afterRender) {
  94304. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94305. }
  94306. }
  94307. this._excludedMeshes[mesh.uniqueId] = null;
  94308. };
  94309. /**
  94310. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94311. * @param mesh mesh to test
  94312. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94313. */
  94314. HighlightLayer.prototype.hasMesh = function (mesh) {
  94315. if (!this._meshes) {
  94316. return false;
  94317. }
  94318. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94319. };
  94320. /**
  94321. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94322. * @param mesh The mesh to highlight
  94323. * @param color The color of the highlight
  94324. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94325. */
  94326. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94327. var _this = this;
  94328. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94329. if (!this._meshes) {
  94330. return;
  94331. }
  94332. var meshHighlight = this._meshes[mesh.uniqueId];
  94333. if (meshHighlight) {
  94334. meshHighlight.color = color;
  94335. }
  94336. else {
  94337. this._meshes[mesh.uniqueId] = {
  94338. mesh: mesh,
  94339. color: color,
  94340. // Lambda required for capture due to Observable this context
  94341. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94342. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94343. _this._defaultStencilReference(mesh);
  94344. }
  94345. else {
  94346. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94347. }
  94348. }),
  94349. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94350. glowEmissiveOnly: glowEmissiveOnly
  94351. };
  94352. }
  94353. this._shouldRender = true;
  94354. };
  94355. /**
  94356. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94357. * @param mesh The mesh to highlight
  94358. */
  94359. HighlightLayer.prototype.removeMesh = function (mesh) {
  94360. if (!this._meshes) {
  94361. return;
  94362. }
  94363. var meshHighlight = this._meshes[mesh.uniqueId];
  94364. if (meshHighlight) {
  94365. if (meshHighlight.observerHighlight) {
  94366. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94367. }
  94368. if (meshHighlight.observerDefault) {
  94369. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94370. }
  94371. delete this._meshes[mesh.uniqueId];
  94372. }
  94373. this._shouldRender = false;
  94374. for (var meshHighlightToCheck in this._meshes) {
  94375. if (this._meshes[meshHighlightToCheck]) {
  94376. this._shouldRender = true;
  94377. break;
  94378. }
  94379. }
  94380. };
  94381. /**
  94382. * Force the stencil to the normal expected value for none glowing parts
  94383. */
  94384. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94385. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94386. };
  94387. /**
  94388. * Free any resources and references associated to a mesh.
  94389. * Internal use
  94390. * @param mesh The mesh to free.
  94391. */
  94392. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94393. this.removeMesh(mesh);
  94394. this.removeExcludedMesh(mesh);
  94395. };
  94396. /**
  94397. * Dispose the highlight layer and free resources.
  94398. */
  94399. HighlightLayer.prototype.dispose = function () {
  94400. if (this._meshes) {
  94401. // Clean mesh references
  94402. for (var id in this._meshes) {
  94403. var meshHighlight = this._meshes[id];
  94404. if (meshHighlight && meshHighlight.mesh) {
  94405. if (meshHighlight.observerHighlight) {
  94406. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94407. }
  94408. if (meshHighlight.observerDefault) {
  94409. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94410. }
  94411. }
  94412. }
  94413. this._meshes = null;
  94414. }
  94415. if (this._excludedMeshes) {
  94416. for (var id in this._excludedMeshes) {
  94417. var meshHighlight = this._excludedMeshes[id];
  94418. if (meshHighlight) {
  94419. if (meshHighlight.beforeRender) {
  94420. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94421. }
  94422. if (meshHighlight.afterRender) {
  94423. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94424. }
  94425. }
  94426. }
  94427. this._excludedMeshes = null;
  94428. }
  94429. _super.prototype.dispose.call(this);
  94430. };
  94431. /**
  94432. * Gets the class name of the effect layer
  94433. * @returns the string with the class name of the effect layer
  94434. */
  94435. HighlightLayer.prototype.getClassName = function () {
  94436. return "HighlightLayer";
  94437. };
  94438. /**
  94439. * Serializes this Highlight layer
  94440. * @returns a serialized Highlight layer object
  94441. */
  94442. HighlightLayer.prototype.serialize = function () {
  94443. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94444. serializationObject.customType = "BABYLON.HighlightLayer";
  94445. // Highlighted meshes
  94446. serializationObject.meshes = [];
  94447. if (this._meshes) {
  94448. for (var m in this._meshes) {
  94449. var mesh = this._meshes[m];
  94450. if (mesh) {
  94451. serializationObject.meshes.push({
  94452. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94453. color: mesh.color.asArray(),
  94454. meshId: mesh.mesh.id
  94455. });
  94456. }
  94457. }
  94458. }
  94459. // Excluded meshes
  94460. serializationObject.excludedMeshes = [];
  94461. if (this._excludedMeshes) {
  94462. for (var e in this._excludedMeshes) {
  94463. var excludedMesh = this._excludedMeshes[e];
  94464. if (excludedMesh) {
  94465. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94466. }
  94467. }
  94468. }
  94469. return serializationObject;
  94470. };
  94471. /**
  94472. * Creates a Highlight layer from parsed Highlight layer data
  94473. * @param parsedHightlightLayer defines the Highlight layer data
  94474. * @param scene defines the current scene
  94475. * @param rootUrl defines the root URL containing the Highlight layer information
  94476. * @returns a parsed Highlight layer
  94477. */
  94478. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94479. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94480. var index;
  94481. // Excluded meshes
  94482. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94483. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94484. if (mesh) {
  94485. hl.addExcludedMesh(mesh);
  94486. }
  94487. }
  94488. // Included meshes
  94489. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94490. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94491. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94492. if (mesh) {
  94493. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94494. }
  94495. }
  94496. return hl;
  94497. };
  94498. /**
  94499. * Effect Name of the highlight layer.
  94500. */
  94501. HighlightLayer.EffectName = "HighlightLayer";
  94502. /**
  94503. * The neutral color used during the preparation of the glow effect.
  94504. * This is black by default as the blend operation is a blend operation.
  94505. */
  94506. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94507. /**
  94508. * Stencil value used for glowing meshes.
  94509. */
  94510. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94511. /**
  94512. * Stencil value used for the other meshes in the scene.
  94513. */
  94514. HighlightLayer.NormalMeshStencilReference = 0x01;
  94515. __decorate([
  94516. BABYLON.serialize()
  94517. ], HighlightLayer.prototype, "innerGlow", void 0);
  94518. __decorate([
  94519. BABYLON.serialize()
  94520. ], HighlightLayer.prototype, "outerGlow", void 0);
  94521. __decorate([
  94522. BABYLON.serialize()
  94523. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94524. __decorate([
  94525. BABYLON.serialize()
  94526. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94527. __decorate([
  94528. BABYLON.serialize("options")
  94529. ], HighlightLayer.prototype, "_options", void 0);
  94530. return HighlightLayer;
  94531. }(BABYLON.EffectLayer));
  94532. BABYLON.HighlightLayer = HighlightLayer;
  94533. })(BABYLON || (BABYLON = {}));
  94534. //# sourceMappingURL=babylon.highlightLayer.js.map
  94535. var BABYLON;
  94536. (function (BABYLON) {
  94537. /**
  94538. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94539. *
  94540. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94541. * glowy meshes to your scene.
  94542. *
  94543. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94544. */
  94545. var GlowLayer = /** @class */ (function (_super) {
  94546. __extends(GlowLayer, _super);
  94547. /**
  94548. * Instantiates a new glow Layer and references it to the scene.
  94549. * @param name The name of the layer
  94550. * @param scene The scene to use the layer in
  94551. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94552. */
  94553. function GlowLayer(name, scene, options) {
  94554. var _this = _super.call(this, name, scene) || this;
  94555. _this._intensity = 1.0;
  94556. _this._includedOnlyMeshes = [];
  94557. _this._excludedMeshes = [];
  94558. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94559. // Adapt options
  94560. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94561. // Initialize the layer
  94562. _this._init({
  94563. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94564. camera: _this._options.camera,
  94565. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94566. mainTextureRatio: _this._options.mainTextureRatio
  94567. });
  94568. return _this;
  94569. }
  94570. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94571. /**
  94572. * Gets the kernel size of the blur.
  94573. */
  94574. get: function () {
  94575. return this._horizontalBlurPostprocess1.kernel;
  94576. },
  94577. /**
  94578. * Sets the kernel size of the blur.
  94579. */
  94580. set: function (value) {
  94581. this._horizontalBlurPostprocess1.kernel = value;
  94582. this._verticalBlurPostprocess1.kernel = value;
  94583. this._horizontalBlurPostprocess2.kernel = value;
  94584. this._verticalBlurPostprocess2.kernel = value;
  94585. },
  94586. enumerable: true,
  94587. configurable: true
  94588. });
  94589. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94590. /**
  94591. * Gets the glow intensity.
  94592. */
  94593. get: function () {
  94594. return this._intensity;
  94595. },
  94596. /**
  94597. * Sets the glow intensity.
  94598. */
  94599. set: function (value) {
  94600. this._intensity = value;
  94601. },
  94602. enumerable: true,
  94603. configurable: true
  94604. });
  94605. /**
  94606. * Get the effect name of the layer.
  94607. * @return The effect name
  94608. */
  94609. GlowLayer.prototype.getEffectName = function () {
  94610. return GlowLayer.EffectName;
  94611. };
  94612. /**
  94613. * Create the merge effect. This is the shader use to blit the information back
  94614. * to the main canvas at the end of the scene rendering.
  94615. */
  94616. GlowLayer.prototype._createMergeEffect = function () {
  94617. // Effect
  94618. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94619. };
  94620. /**
  94621. * Creates the render target textures and post processes used in the glow layer.
  94622. */
  94623. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94624. var _this = this;
  94625. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94626. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94627. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94628. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94629. var textureType = 0;
  94630. if (this._engine.getCaps().textureHalfFloatRender) {
  94631. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94632. }
  94633. else {
  94634. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94635. }
  94636. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94637. width: blurTextureWidth,
  94638. height: blurTextureHeight
  94639. }, this._scene, false, true, textureType);
  94640. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94641. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94642. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94643. this._blurTexture1.renderParticles = false;
  94644. this._blurTexture1.ignoreCameraViewport = true;
  94645. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  94646. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  94647. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  94648. width: blurTextureWidth2,
  94649. height: blurTextureHeight2
  94650. }, this._scene, false, true, textureType);
  94651. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94652. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94653. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94654. this._blurTexture2.renderParticles = false;
  94655. this._blurTexture2.ignoreCameraViewport = true;
  94656. this._textures = [this._blurTexture1, this._blurTexture2];
  94657. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94658. width: blurTextureWidth,
  94659. height: blurTextureHeight
  94660. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94661. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  94662. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  94663. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  94664. effect.setTexture("textureSampler", _this._mainTexture);
  94665. });
  94666. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94667. width: blurTextureWidth,
  94668. height: blurTextureHeight
  94669. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94670. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94671. width: blurTextureWidth2,
  94672. height: blurTextureHeight2
  94673. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94674. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  94675. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  94676. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  94677. effect.setTexture("textureSampler", _this._blurTexture1);
  94678. });
  94679. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94680. width: blurTextureWidth2,
  94681. height: blurTextureHeight2
  94682. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94683. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94684. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94685. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94686. this._mainTexture.samples = this._options.mainTextureSamples;
  94687. this._mainTexture.onAfterUnbindObservable.add(function () {
  94688. var internalTexture = _this._blurTexture1.getInternalTexture();
  94689. if (internalTexture) {
  94690. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94691. internalTexture = _this._blurTexture2.getInternalTexture();
  94692. if (internalTexture) {
  94693. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94694. }
  94695. }
  94696. });
  94697. // Prevent autoClear.
  94698. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94699. };
  94700. /**
  94701. * Checks for the readiness of the element composing the layer.
  94702. * @param subMesh the mesh to check for
  94703. * @param useInstances specify wether or not to use instances to render the mesh
  94704. * @param emissiveTexture the associated emissive texture used to generate the glow
  94705. * @return true if ready otherwise, false
  94706. */
  94707. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94708. var material = subMesh.getMaterial();
  94709. var mesh = subMesh.getRenderingMesh();
  94710. if (!material || !mesh) {
  94711. return false;
  94712. }
  94713. var emissiveTexture = material.emissiveTexture;
  94714. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94715. };
  94716. /**
  94717. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94718. */
  94719. GlowLayer.prototype.needStencil = function () {
  94720. return false;
  94721. };
  94722. /**
  94723. * Implementation specific of rendering the generating effect on the main canvas.
  94724. * @param effect The effect used to render through
  94725. */
  94726. GlowLayer.prototype._internalRender = function (effect) {
  94727. // Texture
  94728. effect.setTexture("textureSampler", this._blurTexture1);
  94729. effect.setTexture("textureSampler2", this._blurTexture2);
  94730. effect.setFloat("offset", this._intensity);
  94731. // Cache
  94732. var engine = this._engine;
  94733. var previousStencilBuffer = engine.getStencilBuffer();
  94734. // Draw order
  94735. engine.setStencilBuffer(false);
  94736. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94737. // Draw order
  94738. engine.setStencilBuffer(previousStencilBuffer);
  94739. };
  94740. /**
  94741. * Sets the required values for both the emissive texture and and the main color.
  94742. */
  94743. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94744. var textureLevel = 1.0;
  94745. if (this.customEmissiveTextureSelector) {
  94746. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94747. }
  94748. else {
  94749. if (material) {
  94750. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94751. if (this._emissiveTextureAndColor.texture) {
  94752. textureLevel = this._emissiveTextureAndColor.texture.level;
  94753. }
  94754. }
  94755. else {
  94756. this._emissiveTextureAndColor.texture = null;
  94757. }
  94758. }
  94759. if (this.customEmissiveColorSelector) {
  94760. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94761. }
  94762. else {
  94763. if (material.emissiveColor) {
  94764. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94765. }
  94766. else {
  94767. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94768. }
  94769. }
  94770. };
  94771. /**
  94772. * Returns true if the mesh should render, otherwise false.
  94773. * @param mesh The mesh to render
  94774. * @returns true if it should render otherwise false
  94775. */
  94776. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94777. return this.hasMesh(mesh);
  94778. };
  94779. /**
  94780. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94781. * @param mesh The mesh to exclude from the glow layer
  94782. */
  94783. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94784. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94785. this._excludedMeshes.push(mesh.uniqueId);
  94786. }
  94787. };
  94788. /**
  94789. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94790. * @param mesh The mesh to remove
  94791. */
  94792. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94793. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94794. if (index !== -1) {
  94795. this._excludedMeshes.splice(index, 1);
  94796. }
  94797. };
  94798. /**
  94799. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94800. * @param mesh The mesh to include in the glow layer
  94801. */
  94802. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94803. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94804. this._includedOnlyMeshes.push(mesh.uniqueId);
  94805. }
  94806. };
  94807. /**
  94808. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94809. * @param mesh The mesh to remove
  94810. */
  94811. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94812. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94813. if (index !== -1) {
  94814. this._includedOnlyMeshes.splice(index, 1);
  94815. }
  94816. };
  94817. /**
  94818. * Determine if a given mesh will be used in the glow layer
  94819. * @param mesh The mesh to test
  94820. * @returns true if the mesh will be highlighted by the current glow layer
  94821. */
  94822. GlowLayer.prototype.hasMesh = function (mesh) {
  94823. // Included Mesh
  94824. if (this._includedOnlyMeshes.length) {
  94825. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94826. }
  94827. ;
  94828. // Excluded Mesh
  94829. if (this._excludedMeshes.length) {
  94830. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94831. }
  94832. ;
  94833. return true;
  94834. };
  94835. /**
  94836. * Free any resources and references associated to a mesh.
  94837. * Internal use
  94838. * @param mesh The mesh to free.
  94839. */
  94840. GlowLayer.prototype._disposeMesh = function (mesh) {
  94841. this.removeIncludedOnlyMesh(mesh);
  94842. this.removeExcludedMesh(mesh);
  94843. };
  94844. /**
  94845. * Gets the class name of the effect layer
  94846. * @returns the string with the class name of the effect layer
  94847. */
  94848. GlowLayer.prototype.getClassName = function () {
  94849. return "GlowLayer";
  94850. };
  94851. /**
  94852. * Serializes this glow layer
  94853. * @returns a serialized glow layer object
  94854. */
  94855. GlowLayer.prototype.serialize = function () {
  94856. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94857. serializationObject.customType = "BABYLON.GlowLayer";
  94858. var index;
  94859. // Included meshes
  94860. serializationObject.includedMeshes = [];
  94861. if (this._includedOnlyMeshes.length) {
  94862. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  94863. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  94864. if (mesh) {
  94865. serializationObject.includedMeshes.push(mesh.id);
  94866. }
  94867. }
  94868. }
  94869. // Excluded meshes
  94870. serializationObject.excludedMeshes = [];
  94871. if (this._excludedMeshes.length) {
  94872. for (index = 0; index < this._excludedMeshes.length; index++) {
  94873. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  94874. if (mesh) {
  94875. serializationObject.excludedMeshes.push(mesh.id);
  94876. }
  94877. }
  94878. }
  94879. return serializationObject;
  94880. };
  94881. /**
  94882. * Creates a Glow Layer from parsed glow layer data
  94883. * @param parsedGlowLayer defines glow layer data
  94884. * @param scene defines the current scene
  94885. * @param rootUrl defines the root URL containing the glow layer information
  94886. * @returns a parsed Glow Layer
  94887. */
  94888. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  94889. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  94890. var index;
  94891. // Excluded meshes
  94892. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  94893. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  94894. if (mesh) {
  94895. gl.addExcludedMesh(mesh);
  94896. }
  94897. }
  94898. // Included meshes
  94899. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  94900. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  94901. if (mesh) {
  94902. gl.addIncludedOnlyMesh(mesh);
  94903. }
  94904. }
  94905. return gl;
  94906. };
  94907. /**
  94908. * Effect Name of the layer.
  94909. */
  94910. GlowLayer.EffectName = "GlowLayer";
  94911. /**
  94912. * The default blur kernel size used for the glow.
  94913. */
  94914. GlowLayer.DefaultBlurKernelSize = 32;
  94915. /**
  94916. * The default texture size ratio used for the glow.
  94917. */
  94918. GlowLayer.DefaultTextureRatio = 0.5;
  94919. __decorate([
  94920. BABYLON.serialize()
  94921. ], GlowLayer.prototype, "blurKernelSize", null);
  94922. __decorate([
  94923. BABYLON.serialize()
  94924. ], GlowLayer.prototype, "intensity", null);
  94925. __decorate([
  94926. BABYLON.serialize("options")
  94927. ], GlowLayer.prototype, "_options", void 0);
  94928. return GlowLayer;
  94929. }(BABYLON.EffectLayer));
  94930. BABYLON.GlowLayer = GlowLayer;
  94931. })(BABYLON || (BABYLON = {}));
  94932. //# sourceMappingURL=babylon.glowLayer.js.map
  94933. var BABYLON;
  94934. (function (BABYLON) {
  94935. /**
  94936. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  94937. */
  94938. var AssetTaskState;
  94939. (function (AssetTaskState) {
  94940. /**
  94941. * Initialization
  94942. */
  94943. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  94944. /**
  94945. * Running
  94946. */
  94947. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  94948. /**
  94949. * Done
  94950. */
  94951. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  94952. /**
  94953. * Error
  94954. */
  94955. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  94956. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  94957. /**
  94958. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  94959. */
  94960. var AbstractAssetTask = /** @class */ (function () {
  94961. /**
  94962. * Creates a new {BABYLON.AssetsManager}
  94963. * @param name defines the name of the task
  94964. */
  94965. function AbstractAssetTask(
  94966. /**
  94967. * Task name
  94968. */ name) {
  94969. this.name = name;
  94970. this._isCompleted = false;
  94971. this._taskState = AssetTaskState.INIT;
  94972. }
  94973. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  94974. /**
  94975. * Get if the task is completed
  94976. */
  94977. get: function () {
  94978. return this._isCompleted;
  94979. },
  94980. enumerable: true,
  94981. configurable: true
  94982. });
  94983. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  94984. /**
  94985. * Gets the current state of the task
  94986. */
  94987. get: function () {
  94988. return this._taskState;
  94989. },
  94990. enumerable: true,
  94991. configurable: true
  94992. });
  94993. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  94994. /**
  94995. * Gets the current error object (if task is in error)
  94996. */
  94997. get: function () {
  94998. return this._errorObject;
  94999. },
  95000. enumerable: true,
  95001. configurable: true
  95002. });
  95003. /**
  95004. * Internal only
  95005. * @hidden
  95006. */
  95007. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  95008. if (this._errorObject) {
  95009. return;
  95010. }
  95011. this._errorObject = {
  95012. message: message,
  95013. exception: exception
  95014. };
  95015. };
  95016. /**
  95017. * Execute the current task
  95018. * @param scene defines the scene where you want your assets to be loaded
  95019. * @param onSuccess is a callback called when the task is successfully executed
  95020. * @param onError is a callback called if an error occurs
  95021. */
  95022. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95023. var _this = this;
  95024. this._taskState = AssetTaskState.RUNNING;
  95025. this.runTask(scene, function () {
  95026. _this.onDoneCallback(onSuccess, onError);
  95027. }, function (msg, exception) {
  95028. _this.onErrorCallback(onError, msg, exception);
  95029. });
  95030. };
  95031. /**
  95032. * Execute the current task
  95033. * @param scene defines the scene where you want your assets to be loaded
  95034. * @param onSuccess is a callback called when the task is successfully executed
  95035. * @param onError is a callback called if an error occurs
  95036. */
  95037. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95038. throw new Error("runTask is not implemented");
  95039. };
  95040. /**
  95041. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95042. * This can be used with failed tasks that have the reason for failure fixed.
  95043. */
  95044. AbstractAssetTask.prototype.reset = function () {
  95045. this._taskState = AssetTaskState.INIT;
  95046. };
  95047. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95048. this._taskState = AssetTaskState.ERROR;
  95049. this._errorObject = {
  95050. message: message,
  95051. exception: exception
  95052. };
  95053. if (this.onError) {
  95054. this.onError(this, message, exception);
  95055. }
  95056. onError();
  95057. };
  95058. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95059. try {
  95060. this._taskState = AssetTaskState.DONE;
  95061. this._isCompleted = true;
  95062. if (this.onSuccess) {
  95063. this.onSuccess(this);
  95064. }
  95065. onSuccess();
  95066. }
  95067. catch (e) {
  95068. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95069. }
  95070. };
  95071. return AbstractAssetTask;
  95072. }());
  95073. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95074. /**
  95075. * Class used to share progress information about assets loading
  95076. */
  95077. var AssetsProgressEvent = /** @class */ (function () {
  95078. /**
  95079. * Creates a {BABYLON.AssetsProgressEvent}
  95080. * @param remainingCount defines the number of remaining tasks to process
  95081. * @param totalCount defines the total number of tasks
  95082. * @param task defines the task that was just processed
  95083. */
  95084. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95085. this.remainingCount = remainingCount;
  95086. this.totalCount = totalCount;
  95087. this.task = task;
  95088. }
  95089. return AssetsProgressEvent;
  95090. }());
  95091. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95092. /**
  95093. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95094. */
  95095. var MeshAssetTask = /** @class */ (function (_super) {
  95096. __extends(MeshAssetTask, _super);
  95097. /**
  95098. * Creates a new {BABYLON.MeshAssetTask}
  95099. * @param name defines the name of the task
  95100. * @param meshesNames defines the list of mesh's names you want to load
  95101. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95102. * @param sceneFilename defines the filename of the scene to load from
  95103. */
  95104. function MeshAssetTask(
  95105. /**
  95106. * Defines the name of the task
  95107. */
  95108. name,
  95109. /**
  95110. * Defines the list of mesh's names you want to load
  95111. */
  95112. meshesNames,
  95113. /**
  95114. * Defines the root url to use as a base to load your meshes and associated resources
  95115. */
  95116. rootUrl,
  95117. /**
  95118. * Defines the filename of the scene to load from
  95119. */
  95120. sceneFilename) {
  95121. var _this = _super.call(this, name) || this;
  95122. _this.name = name;
  95123. _this.meshesNames = meshesNames;
  95124. _this.rootUrl = rootUrl;
  95125. _this.sceneFilename = sceneFilename;
  95126. return _this;
  95127. }
  95128. /**
  95129. * Execute the current task
  95130. * @param scene defines the scene where you want your assets to be loaded
  95131. * @param onSuccess is a callback called when the task is successfully executed
  95132. * @param onError is a callback called if an error occurs
  95133. */
  95134. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95135. var _this = this;
  95136. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95137. _this.loadedMeshes = meshes;
  95138. _this.loadedParticleSystems = particleSystems;
  95139. _this.loadedSkeletons = skeletons;
  95140. onSuccess();
  95141. }, null, function (scene, message, exception) {
  95142. onError(message, exception);
  95143. });
  95144. };
  95145. return MeshAssetTask;
  95146. }(AbstractAssetTask));
  95147. BABYLON.MeshAssetTask = MeshAssetTask;
  95148. /**
  95149. * Define a task used by {BABYLON.AssetsManager} to load text content
  95150. */
  95151. var TextFileAssetTask = /** @class */ (function (_super) {
  95152. __extends(TextFileAssetTask, _super);
  95153. /**
  95154. * Creates a new TextFileAssetTask object
  95155. * @param name defines the name of the task
  95156. * @param url defines the location of the file to load
  95157. */
  95158. function TextFileAssetTask(
  95159. /**
  95160. * Defines the name of the task
  95161. */
  95162. name,
  95163. /**
  95164. * Defines the location of the file to load
  95165. */
  95166. url) {
  95167. var _this = _super.call(this, name) || this;
  95168. _this.name = name;
  95169. _this.url = url;
  95170. return _this;
  95171. }
  95172. /**
  95173. * Execute the current task
  95174. * @param scene defines the scene where you want your assets to be loaded
  95175. * @param onSuccess is a callback called when the task is successfully executed
  95176. * @param onError is a callback called if an error occurs
  95177. */
  95178. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95179. var _this = this;
  95180. scene._loadFile(this.url, function (data) {
  95181. _this.text = data;
  95182. onSuccess();
  95183. }, undefined, false, false, function (request, exception) {
  95184. if (request) {
  95185. onError(request.status + " " + request.statusText, exception);
  95186. }
  95187. });
  95188. };
  95189. return TextFileAssetTask;
  95190. }(AbstractAssetTask));
  95191. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95192. /**
  95193. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95194. */
  95195. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95196. __extends(BinaryFileAssetTask, _super);
  95197. /**
  95198. * Creates a new BinaryFileAssetTask object
  95199. * @param name defines the name of the new task
  95200. * @param url defines the location of the file to load
  95201. */
  95202. function BinaryFileAssetTask(
  95203. /**
  95204. * Defines the name of the task
  95205. */
  95206. name,
  95207. /**
  95208. * Defines the location of the file to load
  95209. */
  95210. url) {
  95211. var _this = _super.call(this, name) || this;
  95212. _this.name = name;
  95213. _this.url = url;
  95214. return _this;
  95215. }
  95216. /**
  95217. * Execute the current task
  95218. * @param scene defines the scene where you want your assets to be loaded
  95219. * @param onSuccess is a callback called when the task is successfully executed
  95220. * @param onError is a callback called if an error occurs
  95221. */
  95222. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95223. var _this = this;
  95224. scene._loadFile(this.url, function (data) {
  95225. _this.data = data;
  95226. onSuccess();
  95227. }, undefined, true, true, function (request, exception) {
  95228. if (request) {
  95229. onError(request.status + " " + request.statusText, exception);
  95230. }
  95231. });
  95232. };
  95233. return BinaryFileAssetTask;
  95234. }(AbstractAssetTask));
  95235. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95236. /**
  95237. * Define a task used by {BABYLON.AssetsManager} to load images
  95238. */
  95239. var ImageAssetTask = /** @class */ (function (_super) {
  95240. __extends(ImageAssetTask, _super);
  95241. /**
  95242. * Creates a new ImageAssetTask
  95243. * @param name defines the name of the task
  95244. * @param url defines the location of the image to load
  95245. */
  95246. function ImageAssetTask(
  95247. /**
  95248. * Defines the name of the task
  95249. */
  95250. name,
  95251. /**
  95252. * Defines the location of the image to load
  95253. */
  95254. url) {
  95255. var _this = _super.call(this, name) || this;
  95256. _this.name = name;
  95257. _this.url = url;
  95258. return _this;
  95259. }
  95260. /**
  95261. * Execute the current task
  95262. * @param scene defines the scene where you want your assets to be loaded
  95263. * @param onSuccess is a callback called when the task is successfully executed
  95264. * @param onError is a callback called if an error occurs
  95265. */
  95266. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95267. var _this = this;
  95268. var img = new Image();
  95269. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95270. img.onload = function () {
  95271. _this.image = img;
  95272. onSuccess();
  95273. };
  95274. img.onerror = function (err) {
  95275. onError("Error loading image", err);
  95276. };
  95277. img.src = this.url;
  95278. };
  95279. return ImageAssetTask;
  95280. }(AbstractAssetTask));
  95281. BABYLON.ImageAssetTask = ImageAssetTask;
  95282. /**
  95283. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95284. */
  95285. var TextureAssetTask = /** @class */ (function (_super) {
  95286. __extends(TextureAssetTask, _super);
  95287. /**
  95288. * Creates a new TextureAssetTask object
  95289. * @param name defines the name of the task
  95290. * @param url defines the location of the file to load
  95291. * @param noMipmap defines if mipmap should not be generated (default is false)
  95292. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95293. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95294. */
  95295. function TextureAssetTask(
  95296. /**
  95297. * Defines the name of the task
  95298. */
  95299. name,
  95300. /**
  95301. * Defines the location of the file to load
  95302. */
  95303. url,
  95304. /**
  95305. * Defines if mipmap should not be generated (default is false)
  95306. */
  95307. noMipmap,
  95308. /**
  95309. * Defines if texture must be inverted on Y axis (default is false)
  95310. */
  95311. invertY,
  95312. /**
  95313. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95314. */
  95315. samplingMode) {
  95316. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95317. var _this = _super.call(this, name) || this;
  95318. _this.name = name;
  95319. _this.url = url;
  95320. _this.noMipmap = noMipmap;
  95321. _this.invertY = invertY;
  95322. _this.samplingMode = samplingMode;
  95323. return _this;
  95324. }
  95325. /**
  95326. * Execute the current task
  95327. * @param scene defines the scene where you want your assets to be loaded
  95328. * @param onSuccess is a callback called when the task is successfully executed
  95329. * @param onError is a callback called if an error occurs
  95330. */
  95331. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95332. var onload = function () {
  95333. onSuccess();
  95334. };
  95335. var onerror = function (message, exception) {
  95336. onError(message, exception);
  95337. };
  95338. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95339. };
  95340. return TextureAssetTask;
  95341. }(AbstractAssetTask));
  95342. BABYLON.TextureAssetTask = TextureAssetTask;
  95343. /**
  95344. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95345. */
  95346. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95347. __extends(CubeTextureAssetTask, _super);
  95348. /**
  95349. * Creates a new CubeTextureAssetTask
  95350. * @param name defines the name of the task
  95351. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95352. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95353. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95354. * @param files defines the explicit list of files (undefined by default)
  95355. */
  95356. function CubeTextureAssetTask(
  95357. /**
  95358. * Defines the name of the task
  95359. */
  95360. name,
  95361. /**
  95362. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95363. */
  95364. url,
  95365. /**
  95366. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95367. */
  95368. extensions,
  95369. /**
  95370. * Defines if mipmaps should not be generated (default is false)
  95371. */
  95372. noMipmap,
  95373. /**
  95374. * Defines the explicit list of files (undefined by default)
  95375. */
  95376. files) {
  95377. var _this = _super.call(this, name) || this;
  95378. _this.name = name;
  95379. _this.url = url;
  95380. _this.extensions = extensions;
  95381. _this.noMipmap = noMipmap;
  95382. _this.files = files;
  95383. return _this;
  95384. }
  95385. /**
  95386. * Execute the current task
  95387. * @param scene defines the scene where you want your assets to be loaded
  95388. * @param onSuccess is a callback called when the task is successfully executed
  95389. * @param onError is a callback called if an error occurs
  95390. */
  95391. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95392. var onload = function () {
  95393. onSuccess();
  95394. };
  95395. var onerror = function (message, exception) {
  95396. onError(message, exception);
  95397. };
  95398. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95399. };
  95400. return CubeTextureAssetTask;
  95401. }(AbstractAssetTask));
  95402. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95403. /**
  95404. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95405. */
  95406. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95407. __extends(HDRCubeTextureAssetTask, _super);
  95408. /**
  95409. * Creates a new HDRCubeTextureAssetTask object
  95410. * @param name defines the name of the task
  95411. * @param url defines the location of the file to load
  95412. * @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.
  95413. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95414. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95415. * @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)
  95416. * @param reserved Internal use only
  95417. */
  95418. function HDRCubeTextureAssetTask(
  95419. /**
  95420. * Defines the name of the task
  95421. */
  95422. name,
  95423. /**
  95424. * Defines the location of the file to load
  95425. */
  95426. url,
  95427. /**
  95428. * Defines the desired size (the more it increases the longer the generation will be)
  95429. */
  95430. size,
  95431. /**
  95432. * Defines if mipmaps should not be generated (default is false)
  95433. */
  95434. noMipmap,
  95435. /**
  95436. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95437. */
  95438. generateHarmonics,
  95439. /**
  95440. * 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)
  95441. */
  95442. gammaSpace,
  95443. /**
  95444. * Internal Use Only
  95445. */
  95446. reserved) {
  95447. if (noMipmap === void 0) { noMipmap = false; }
  95448. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95449. if (gammaSpace === void 0) { gammaSpace = false; }
  95450. if (reserved === void 0) { reserved = false; }
  95451. var _this = _super.call(this, name) || this;
  95452. _this.name = name;
  95453. _this.url = url;
  95454. _this.size = size;
  95455. _this.noMipmap = noMipmap;
  95456. _this.generateHarmonics = generateHarmonics;
  95457. _this.gammaSpace = gammaSpace;
  95458. _this.reserved = reserved;
  95459. return _this;
  95460. }
  95461. /**
  95462. * Execute the current task
  95463. * @param scene defines the scene where you want your assets to be loaded
  95464. * @param onSuccess is a callback called when the task is successfully executed
  95465. * @param onError is a callback called if an error occurs
  95466. */
  95467. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95468. var onload = function () {
  95469. onSuccess();
  95470. };
  95471. var onerror = function (message, exception) {
  95472. onError(message, exception);
  95473. };
  95474. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95475. };
  95476. return HDRCubeTextureAssetTask;
  95477. }(AbstractAssetTask));
  95478. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95479. /**
  95480. * This class can be used to easily import assets into a scene
  95481. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95482. */
  95483. var AssetsManager = /** @class */ (function () {
  95484. /**
  95485. * Creates a new AssetsManager
  95486. * @param scene defines the scene to work on
  95487. */
  95488. function AssetsManager(scene) {
  95489. this._isLoading = false;
  95490. this._tasks = new Array();
  95491. this._waitingTasksCount = 0;
  95492. this._totalTasksCount = 0;
  95493. /**
  95494. * Observable called when all tasks are processed
  95495. */
  95496. this.onTaskSuccessObservable = new BABYLON.Observable();
  95497. /**
  95498. * Observable called when a task had an error
  95499. */
  95500. this.onTaskErrorObservable = new BABYLON.Observable();
  95501. /**
  95502. * Observable called when a task is successful
  95503. */
  95504. this.onTasksDoneObservable = new BABYLON.Observable();
  95505. /**
  95506. * Observable called when a task is done (whatever the result is)
  95507. */
  95508. this.onProgressObservable = new BABYLON.Observable();
  95509. /**
  95510. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95511. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95512. */
  95513. this.useDefaultLoadingScreen = true;
  95514. this._scene = scene;
  95515. }
  95516. /**
  95517. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95518. * @param taskName defines the name of the new task
  95519. * @param meshesNames defines the name of meshes to load
  95520. * @param rootUrl defines the root url to use to locate files
  95521. * @param sceneFilename defines the filename of the scene file
  95522. * @returns a new {BABYLON.MeshAssetTask} object
  95523. */
  95524. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95525. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95526. this._tasks.push(task);
  95527. return task;
  95528. };
  95529. /**
  95530. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95531. * @param taskName defines the name of the new task
  95532. * @param url defines the url of the file to load
  95533. * @returns a new {BABYLON.TextFileAssetTask} object
  95534. */
  95535. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95536. var task = new TextFileAssetTask(taskName, url);
  95537. this._tasks.push(task);
  95538. return task;
  95539. };
  95540. /**
  95541. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95542. * @param taskName defines the name of the new task
  95543. * @param url defines the url of the file to load
  95544. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95545. */
  95546. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95547. var task = new BinaryFileAssetTask(taskName, url);
  95548. this._tasks.push(task);
  95549. return task;
  95550. };
  95551. /**
  95552. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95553. * @param taskName defines the name of the new task
  95554. * @param url defines the url of the file to load
  95555. * @returns a new {BABYLON.ImageAssetTask} object
  95556. */
  95557. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95558. var task = new ImageAssetTask(taskName, url);
  95559. this._tasks.push(task);
  95560. return task;
  95561. };
  95562. /**
  95563. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95564. * @param taskName defines the name of the new task
  95565. * @param url defines the url of the file to load
  95566. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95567. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95568. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95569. * @returns a new {BABYLON.TextureAssetTask} object
  95570. */
  95571. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95573. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95574. this._tasks.push(task);
  95575. return task;
  95576. };
  95577. /**
  95578. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95579. * @param taskName defines the name of the new task
  95580. * @param url defines the url of the file to load
  95581. * @param extensions defines the extension to use to load the cube map (can be null)
  95582. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95583. * @param files defines the list of files to load (can be null)
  95584. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95585. */
  95586. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95587. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95588. this._tasks.push(task);
  95589. return task;
  95590. };
  95591. /**
  95592. *
  95593. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95594. * @param taskName defines the name of the new task
  95595. * @param url defines the url of the file to load
  95596. * @param size defines the size you want for the cubemap (can be null)
  95597. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95598. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95599. * @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)
  95600. * @param reserved Internal use only
  95601. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95602. */
  95603. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95604. if (noMipmap === void 0) { noMipmap = false; }
  95605. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95606. if (gammaSpace === void 0) { gammaSpace = false; }
  95607. if (reserved === void 0) { reserved = false; }
  95608. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95609. this._tasks.push(task);
  95610. return task;
  95611. };
  95612. /**
  95613. * Remove a task from the assets manager.
  95614. * @param task the task to remove
  95615. */
  95616. AssetsManager.prototype.removeTask = function (task) {
  95617. var index = this._tasks.indexOf(task);
  95618. if (index > -1) {
  95619. this._tasks.splice(index, 1);
  95620. }
  95621. };
  95622. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95623. this._waitingTasksCount--;
  95624. try {
  95625. if (this.onProgress) {
  95626. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95627. }
  95628. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95629. }
  95630. catch (e) {
  95631. BABYLON.Tools.Error("Error running progress callbacks.");
  95632. console.log(e);
  95633. }
  95634. if (this._waitingTasksCount === 0) {
  95635. try {
  95636. if (this.onFinish) {
  95637. this.onFinish(this._tasks);
  95638. }
  95639. // Let's remove successfull tasks
  95640. var currentTasks = this._tasks.slice();
  95641. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95642. var task = currentTasks_1[_i];
  95643. if (task.taskState === AssetTaskState.DONE) {
  95644. var index = this._tasks.indexOf(task);
  95645. if (index > -1) {
  95646. this._tasks.splice(index, 1);
  95647. }
  95648. }
  95649. }
  95650. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95651. }
  95652. catch (e) {
  95653. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  95654. console.log(e);
  95655. }
  95656. this._isLoading = false;
  95657. this._scene.getEngine().hideLoadingUI();
  95658. }
  95659. };
  95660. AssetsManager.prototype._runTask = function (task) {
  95661. var _this = this;
  95662. var done = function () {
  95663. try {
  95664. if (_this.onTaskSuccess) {
  95665. _this.onTaskSuccess(task);
  95666. }
  95667. _this.onTaskSuccessObservable.notifyObservers(task);
  95668. _this._decreaseWaitingTasksCount(task);
  95669. }
  95670. catch (e) {
  95671. error("Error executing task success callbacks", e);
  95672. }
  95673. };
  95674. var error = function (message, exception) {
  95675. task._setErrorObject(message, exception);
  95676. if (_this.onTaskError) {
  95677. _this.onTaskError(task);
  95678. }
  95679. _this.onTaskErrorObservable.notifyObservers(task);
  95680. _this._decreaseWaitingTasksCount(task);
  95681. };
  95682. task.run(this._scene, done, error);
  95683. };
  95684. /**
  95685. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95686. * @return the current instance of the {BABYLON.AssetsManager}
  95687. */
  95688. AssetsManager.prototype.reset = function () {
  95689. this._isLoading = false;
  95690. this._tasks = new Array();
  95691. return this;
  95692. };
  95693. /**
  95694. * Start the loading process
  95695. * @return the current instance of the {BABYLON.AssetsManager}
  95696. */
  95697. AssetsManager.prototype.load = function () {
  95698. if (this._isLoading) {
  95699. return this;
  95700. }
  95701. this._isLoading = true;
  95702. this._waitingTasksCount = this._tasks.length;
  95703. this._totalTasksCount = this._tasks.length;
  95704. if (this._waitingTasksCount === 0) {
  95705. this._isLoading = false;
  95706. if (this.onFinish) {
  95707. this.onFinish(this._tasks);
  95708. }
  95709. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95710. return this;
  95711. }
  95712. if (this.useDefaultLoadingScreen) {
  95713. this._scene.getEngine().displayLoadingUI();
  95714. }
  95715. for (var index = 0; index < this._tasks.length; index++) {
  95716. var task = this._tasks[index];
  95717. if (task.taskState === AssetTaskState.INIT) {
  95718. this._runTask(task);
  95719. }
  95720. }
  95721. return this;
  95722. };
  95723. return AssetsManager;
  95724. }());
  95725. BABYLON.AssetsManager = AssetsManager;
  95726. })(BABYLON || (BABYLON = {}));
  95727. //# sourceMappingURL=babylon.assetsManager.js.map
  95728. var BABYLON;
  95729. (function (BABYLON) {
  95730. var serializedGeometries = [];
  95731. var serializeGeometry = function (geometry, serializationGeometries) {
  95732. if (serializedGeometries[geometry.id]) {
  95733. return;
  95734. }
  95735. if (geometry.doNotSerialize) {
  95736. return;
  95737. }
  95738. if (geometry instanceof BABYLON.BoxGeometry) {
  95739. serializationGeometries.boxes.push(geometry.serialize());
  95740. }
  95741. else if (geometry instanceof BABYLON.SphereGeometry) {
  95742. serializationGeometries.spheres.push(geometry.serialize());
  95743. }
  95744. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95745. serializationGeometries.cylinders.push(geometry.serialize());
  95746. }
  95747. else if (geometry instanceof BABYLON.TorusGeometry) {
  95748. serializationGeometries.toruses.push(geometry.serialize());
  95749. }
  95750. else if (geometry instanceof BABYLON.GroundGeometry) {
  95751. serializationGeometries.grounds.push(geometry.serialize());
  95752. }
  95753. else if (geometry instanceof BABYLON.Plane) {
  95754. serializationGeometries.planes.push(geometry.serialize());
  95755. }
  95756. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95757. serializationGeometries.torusKnots.push(geometry.serialize());
  95758. }
  95759. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95760. throw new Error("Unknown primitive type");
  95761. }
  95762. else {
  95763. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95764. }
  95765. serializedGeometries[geometry.id] = true;
  95766. };
  95767. var serializeMesh = function (mesh, serializationScene) {
  95768. var serializationObject = {};
  95769. // Geometry
  95770. var geometry = mesh._geometry;
  95771. if (geometry) {
  95772. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95773. // 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
  95774. serializeGeometry(geometry, serializationScene.geometries);
  95775. }
  95776. }
  95777. // Custom
  95778. if (mesh.serialize) {
  95779. mesh.serialize(serializationObject);
  95780. }
  95781. return serializationObject;
  95782. };
  95783. var finalizeSingleMesh = function (mesh, serializationObject) {
  95784. //only works if the mesh is already loaded
  95785. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95786. //serialize material
  95787. if (mesh.material) {
  95788. if (mesh.material instanceof BABYLON.MultiMaterial) {
  95789. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95790. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95791. serializationObject.multiMaterials.push(mesh.material.serialize());
  95792. }
  95793. }
  95794. else {
  95795. serializationObject.materials = serializationObject.materials || [];
  95796. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95797. serializationObject.materials.push(mesh.material.serialize());
  95798. }
  95799. }
  95800. }
  95801. //serialize geometry
  95802. var geometry = mesh._geometry;
  95803. if (geometry) {
  95804. if (!serializationObject.geometries) {
  95805. serializationObject.geometries = {};
  95806. serializationObject.geometries.boxes = [];
  95807. serializationObject.geometries.spheres = [];
  95808. serializationObject.geometries.cylinders = [];
  95809. serializationObject.geometries.toruses = [];
  95810. serializationObject.geometries.grounds = [];
  95811. serializationObject.geometries.planes = [];
  95812. serializationObject.geometries.torusKnots = [];
  95813. serializationObject.geometries.vertexData = [];
  95814. }
  95815. serializeGeometry(geometry, serializationObject.geometries);
  95816. }
  95817. // Skeletons
  95818. if (mesh.skeleton) {
  95819. serializationObject.skeletons = serializationObject.skeletons || [];
  95820. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95821. }
  95822. //serialize the actual mesh
  95823. serializationObject.meshes = serializationObject.meshes || [];
  95824. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95825. }
  95826. };
  95827. var SceneSerializer = /** @class */ (function () {
  95828. function SceneSerializer() {
  95829. }
  95830. SceneSerializer.ClearCache = function () {
  95831. serializedGeometries = [];
  95832. };
  95833. SceneSerializer.Serialize = function (scene) {
  95834. var serializationObject = {};
  95835. SceneSerializer.ClearCache();
  95836. // Scene
  95837. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95838. serializationObject.autoClear = scene.autoClear;
  95839. serializationObject.clearColor = scene.clearColor.asArray();
  95840. serializationObject.ambientColor = scene.ambientColor.asArray();
  95841. serializationObject.gravity = scene.gravity.asArray();
  95842. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  95843. serializationObject.workerCollisions = scene.workerCollisions;
  95844. // Fog
  95845. if (scene.fogMode && scene.fogMode !== 0) {
  95846. serializationObject.fogMode = scene.fogMode;
  95847. serializationObject.fogColor = scene.fogColor.asArray();
  95848. serializationObject.fogStart = scene.fogStart;
  95849. serializationObject.fogEnd = scene.fogEnd;
  95850. serializationObject.fogDensity = scene.fogDensity;
  95851. }
  95852. //Physics
  95853. if (scene.isPhysicsEnabled()) {
  95854. var physicEngine = scene.getPhysicsEngine();
  95855. if (physicEngine) {
  95856. serializationObject.physicsEnabled = true;
  95857. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  95858. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  95859. }
  95860. }
  95861. // Metadata
  95862. if (scene.metadata) {
  95863. serializationObject.metadata = scene.metadata;
  95864. }
  95865. // Morph targets
  95866. serializationObject.morphTargetManagers = [];
  95867. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  95868. var abstractMesh = _a[_i];
  95869. var manager = abstractMesh.morphTargetManager;
  95870. if (manager) {
  95871. serializationObject.morphTargetManagers.push(manager.serialize());
  95872. }
  95873. }
  95874. // Lights
  95875. serializationObject.lights = [];
  95876. var index;
  95877. var light;
  95878. for (index = 0; index < scene.lights.length; index++) {
  95879. light = scene.lights[index];
  95880. if (!light.doNotSerialize) {
  95881. serializationObject.lights.push(light.serialize());
  95882. }
  95883. }
  95884. // Cameras
  95885. serializationObject.cameras = [];
  95886. for (index = 0; index < scene.cameras.length; index++) {
  95887. var camera = scene.cameras[index];
  95888. if (!camera.doNotSerialize) {
  95889. serializationObject.cameras.push(camera.serialize());
  95890. }
  95891. }
  95892. if (scene.activeCamera) {
  95893. serializationObject.activeCameraID = scene.activeCamera.id;
  95894. }
  95895. // Animations
  95896. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  95897. // Materials
  95898. serializationObject.materials = [];
  95899. serializationObject.multiMaterials = [];
  95900. var material;
  95901. for (index = 0; index < scene.materials.length; index++) {
  95902. material = scene.materials[index];
  95903. if (!material.doNotSerialize) {
  95904. serializationObject.materials.push(material.serialize());
  95905. }
  95906. }
  95907. // MultiMaterials
  95908. serializationObject.multiMaterials = [];
  95909. for (index = 0; index < scene.multiMaterials.length; index++) {
  95910. var multiMaterial = scene.multiMaterials[index];
  95911. serializationObject.multiMaterials.push(multiMaterial.serialize());
  95912. }
  95913. // Environment texture
  95914. if (scene.environmentTexture) {
  95915. serializationObject.environmentTexture = scene.environmentTexture.name;
  95916. }
  95917. // Skeletons
  95918. serializationObject.skeletons = [];
  95919. for (index = 0; index < scene.skeletons.length; index++) {
  95920. var skeleton = scene.skeletons[index];
  95921. if (!skeleton.doNotSerialize) {
  95922. serializationObject.skeletons.push(skeleton.serialize());
  95923. }
  95924. }
  95925. // Transform nodes
  95926. serializationObject.transformNodes = [];
  95927. for (index = 0; index < scene.transformNodes.length; index++) {
  95928. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  95929. }
  95930. // Geometries
  95931. serializationObject.geometries = {};
  95932. serializationObject.geometries.boxes = [];
  95933. serializationObject.geometries.spheres = [];
  95934. serializationObject.geometries.cylinders = [];
  95935. serializationObject.geometries.toruses = [];
  95936. serializationObject.geometries.grounds = [];
  95937. serializationObject.geometries.planes = [];
  95938. serializationObject.geometries.torusKnots = [];
  95939. serializationObject.geometries.vertexData = [];
  95940. serializedGeometries = [];
  95941. var geometries = scene.getGeometries();
  95942. for (index = 0; index < geometries.length; index++) {
  95943. var geometry = geometries[index];
  95944. if (geometry.isReady()) {
  95945. serializeGeometry(geometry, serializationObject.geometries);
  95946. }
  95947. }
  95948. // Meshes
  95949. serializationObject.meshes = [];
  95950. for (index = 0; index < scene.meshes.length; index++) {
  95951. var abstractMesh = scene.meshes[index];
  95952. if (abstractMesh instanceof BABYLON.Mesh) {
  95953. var mesh = abstractMesh;
  95954. if (!mesh.doNotSerialize) {
  95955. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95956. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95957. }
  95958. }
  95959. }
  95960. }
  95961. // Particles Systems
  95962. serializationObject.particleSystems = [];
  95963. for (index = 0; index < scene.particleSystems.length; index++) {
  95964. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  95965. }
  95966. // Lens flares
  95967. serializationObject.lensFlareSystems = [];
  95968. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  95969. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  95970. }
  95971. // Shadows
  95972. serializationObject.shadowGenerators = [];
  95973. for (index = 0; index < scene.lights.length; index++) {
  95974. light = scene.lights[index];
  95975. var shadowGenerator = light.getShadowGenerator();
  95976. if (shadowGenerator) {
  95977. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  95978. }
  95979. }
  95980. // Action Manager
  95981. if (scene.actionManager) {
  95982. serializationObject.actions = scene.actionManager.serialize("scene");
  95983. }
  95984. // Audio
  95985. serializationObject.sounds = [];
  95986. for (index = 0; index < scene.soundTracks.length; index++) {
  95987. var soundtrack = scene.soundTracks[index];
  95988. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  95989. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  95990. }
  95991. }
  95992. // Effect layers
  95993. serializationObject.effectLayers = [];
  95994. for (index = 0; index < scene.effectLayers.length; index++) {
  95995. var layer = scene.effectLayers[index];
  95996. if (layer.serialize) {
  95997. serializationObject.effectLayers.push(layer.serialize());
  95998. }
  95999. }
  96000. return serializationObject;
  96001. };
  96002. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  96003. if (withParents === void 0) { withParents = false; }
  96004. if (withChildren === void 0) { withChildren = false; }
  96005. var serializationObject = {};
  96006. SceneSerializer.ClearCache();
  96007. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  96008. if (withParents || withChildren) {
  96009. //deliberate for loop! not for each, appended should be processed as well.
  96010. for (var i = 0; i < toSerialize.length; ++i) {
  96011. if (withChildren) {
  96012. toSerialize[i].getDescendants().forEach(function (node) {
  96013. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  96014. toSerialize.push(node);
  96015. }
  96016. });
  96017. }
  96018. //make sure the array doesn't contain the object already
  96019. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  96020. toSerialize.push(toSerialize[i].parent);
  96021. }
  96022. }
  96023. }
  96024. toSerialize.forEach(function (mesh) {
  96025. finalizeSingleMesh(mesh, serializationObject);
  96026. });
  96027. return serializationObject;
  96028. };
  96029. return SceneSerializer;
  96030. }());
  96031. BABYLON.SceneSerializer = SceneSerializer;
  96032. })(BABYLON || (BABYLON = {}));
  96033. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96034. var BABYLON;
  96035. (function (BABYLON) {
  96036. var ReflectionProbe = /** @class */ (function () {
  96037. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96038. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96039. var _this = this;
  96040. this.name = name;
  96041. this._viewMatrix = BABYLON.Matrix.Identity();
  96042. this._target = BABYLON.Vector3.Zero();
  96043. this._add = BABYLON.Vector3.Zero();
  96044. this._invertYAxis = false;
  96045. this.position = BABYLON.Vector3.Zero();
  96046. this._scene = scene;
  96047. this._scene.reflectionProbes.push(this);
  96048. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96049. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96050. switch (faceIndex) {
  96051. case 0:
  96052. _this._add.copyFromFloats(1, 0, 0);
  96053. break;
  96054. case 1:
  96055. _this._add.copyFromFloats(-1, 0, 0);
  96056. break;
  96057. case 2:
  96058. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96059. break;
  96060. case 3:
  96061. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96062. break;
  96063. case 4:
  96064. _this._add.copyFromFloats(0, 0, 1);
  96065. break;
  96066. case 5:
  96067. _this._add.copyFromFloats(0, 0, -1);
  96068. break;
  96069. }
  96070. if (_this._attachedMesh) {
  96071. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96072. }
  96073. _this.position.addToRef(_this._add, _this._target);
  96074. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96075. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96076. scene._forcedViewPosition = _this.position;
  96077. });
  96078. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96079. scene._forcedViewPosition = null;
  96080. scene.updateTransformMatrix(true);
  96081. });
  96082. if (scene.activeCamera) {
  96083. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96084. }
  96085. }
  96086. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96087. get: function () {
  96088. return this._renderTargetTexture.samples;
  96089. },
  96090. set: function (value) {
  96091. this._renderTargetTexture.samples = value;
  96092. },
  96093. enumerable: true,
  96094. configurable: true
  96095. });
  96096. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96097. get: function () {
  96098. return this._renderTargetTexture.refreshRate;
  96099. },
  96100. set: function (value) {
  96101. this._renderTargetTexture.refreshRate = value;
  96102. },
  96103. enumerable: true,
  96104. configurable: true
  96105. });
  96106. ReflectionProbe.prototype.getScene = function () {
  96107. return this._scene;
  96108. };
  96109. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96110. get: function () {
  96111. return this._renderTargetTexture;
  96112. },
  96113. enumerable: true,
  96114. configurable: true
  96115. });
  96116. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96117. get: function () {
  96118. return this._renderTargetTexture.renderList;
  96119. },
  96120. enumerable: true,
  96121. configurable: true
  96122. });
  96123. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96124. this._attachedMesh = mesh;
  96125. };
  96126. /**
  96127. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96128. *
  96129. * @param renderingGroupId The rendering group id corresponding to its index
  96130. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96131. */
  96132. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96133. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96134. };
  96135. ReflectionProbe.prototype.dispose = function () {
  96136. var index = this._scene.reflectionProbes.indexOf(this);
  96137. if (index !== -1) {
  96138. // Remove from the scene if found
  96139. this._scene.reflectionProbes.splice(index, 1);
  96140. }
  96141. if (this._renderTargetTexture) {
  96142. this._renderTargetTexture.dispose();
  96143. this._renderTargetTexture = null;
  96144. }
  96145. };
  96146. return ReflectionProbe;
  96147. }());
  96148. BABYLON.ReflectionProbe = ReflectionProbe;
  96149. })(BABYLON || (BABYLON = {}));
  96150. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96151. var BABYLON;
  96152. (function (BABYLON) {
  96153. var Layer = /** @class */ (function () {
  96154. function Layer(name, imgUrl, scene, isBackground, color) {
  96155. this.name = name;
  96156. this.scale = new BABYLON.Vector2(1, 1);
  96157. this.offset = new BABYLON.Vector2(0, 0);
  96158. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96159. this.layerMask = 0x0FFFFFFF;
  96160. this._vertexBuffers = {};
  96161. // Events
  96162. /**
  96163. * An event triggered when the layer is disposed.
  96164. */
  96165. this.onDisposeObservable = new BABYLON.Observable();
  96166. /**
  96167. * An event triggered before rendering the scene
  96168. */
  96169. this.onBeforeRenderObservable = new BABYLON.Observable();
  96170. /**
  96171. * An event triggered after rendering the scene
  96172. */
  96173. this.onAfterRenderObservable = new BABYLON.Observable();
  96174. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96175. this.isBackground = isBackground === undefined ? true : isBackground;
  96176. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96177. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96178. this._scene.layers.push(this);
  96179. var engine = this._scene.getEngine();
  96180. // VBO
  96181. var vertices = [];
  96182. vertices.push(1, 1);
  96183. vertices.push(-1, 1);
  96184. vertices.push(-1, -1);
  96185. vertices.push(1, -1);
  96186. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96187. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96188. this._createIndexBuffer();
  96189. // Effects
  96190. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96191. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96192. }
  96193. Object.defineProperty(Layer.prototype, "onDispose", {
  96194. set: function (callback) {
  96195. if (this._onDisposeObserver) {
  96196. this.onDisposeObservable.remove(this._onDisposeObserver);
  96197. }
  96198. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96199. },
  96200. enumerable: true,
  96201. configurable: true
  96202. });
  96203. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96204. set: function (callback) {
  96205. if (this._onBeforeRenderObserver) {
  96206. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96207. }
  96208. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96209. },
  96210. enumerable: true,
  96211. configurable: true
  96212. });
  96213. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96214. set: function (callback) {
  96215. if (this._onAfterRenderObserver) {
  96216. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96217. }
  96218. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96219. },
  96220. enumerable: true,
  96221. configurable: true
  96222. });
  96223. Layer.prototype._createIndexBuffer = function () {
  96224. var engine = this._scene.getEngine();
  96225. // Indices
  96226. var indices = [];
  96227. indices.push(0);
  96228. indices.push(1);
  96229. indices.push(2);
  96230. indices.push(0);
  96231. indices.push(2);
  96232. indices.push(3);
  96233. this._indexBuffer = engine.createIndexBuffer(indices);
  96234. };
  96235. Layer.prototype._rebuild = function () {
  96236. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96237. if (vb) {
  96238. vb._rebuild();
  96239. }
  96240. this._createIndexBuffer();
  96241. };
  96242. Layer.prototype.render = function () {
  96243. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96244. // Check
  96245. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96246. return;
  96247. var engine = this._scene.getEngine();
  96248. this.onBeforeRenderObservable.notifyObservers(this);
  96249. // Render
  96250. engine.enableEffect(currentEffect);
  96251. engine.setState(false);
  96252. // Texture
  96253. currentEffect.setTexture("textureSampler", this.texture);
  96254. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96255. // Color
  96256. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96257. // Scale / offset
  96258. currentEffect.setVector2("offset", this.offset);
  96259. currentEffect.setVector2("scale", this.scale);
  96260. // VBOs
  96261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96262. // Draw order
  96263. if (!this.alphaTest) {
  96264. engine.setAlphaMode(this.alphaBlendingMode);
  96265. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96266. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96267. }
  96268. else {
  96269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96270. }
  96271. this.onAfterRenderObservable.notifyObservers(this);
  96272. };
  96273. Layer.prototype.dispose = function () {
  96274. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96275. if (vertexBuffer) {
  96276. vertexBuffer.dispose();
  96277. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96278. }
  96279. if (this._indexBuffer) {
  96280. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96281. this._indexBuffer = null;
  96282. }
  96283. if (this.texture) {
  96284. this.texture.dispose();
  96285. this.texture = null;
  96286. }
  96287. // Remove from scene
  96288. var index = this._scene.layers.indexOf(this);
  96289. this._scene.layers.splice(index, 1);
  96290. // Callback
  96291. this.onDisposeObservable.notifyObservers(this);
  96292. this.onDisposeObservable.clear();
  96293. this.onAfterRenderObservable.clear();
  96294. this.onBeforeRenderObservable.clear();
  96295. };
  96296. return Layer;
  96297. }());
  96298. BABYLON.Layer = Layer;
  96299. })(BABYLON || (BABYLON = {}));
  96300. //# sourceMappingURL=babylon.layer.js.map
  96301. var BABYLON;
  96302. (function (BABYLON) {
  96303. var TextureTools = /** @class */ (function () {
  96304. function TextureTools() {
  96305. }
  96306. /**
  96307. * Uses the GPU to create a copy texture rescaled at a given size
  96308. * @param texture Texture to copy from
  96309. * @param width Desired width
  96310. * @param height Desired height
  96311. * @return Generated texture
  96312. */
  96313. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96314. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96315. var scene = texture.getScene();
  96316. var engine = scene.getEngine();
  96317. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96318. rtt.wrapU = texture.wrapU;
  96319. rtt.wrapV = texture.wrapV;
  96320. rtt.uOffset = texture.uOffset;
  96321. rtt.vOffset = texture.vOffset;
  96322. rtt.uScale = texture.uScale;
  96323. rtt.vScale = texture.vScale;
  96324. rtt.uAng = texture.uAng;
  96325. rtt.vAng = texture.vAng;
  96326. rtt.wAng = texture.wAng;
  96327. rtt.coordinatesIndex = texture.coordinatesIndex;
  96328. rtt.level = texture.level;
  96329. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96330. rtt._texture.isReady = false;
  96331. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96332. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96333. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96334. passPostProcess.getEffect().executeWhenCompiled(function () {
  96335. passPostProcess.onApply = function (effect) {
  96336. effect.setTexture("textureSampler", texture);
  96337. };
  96338. var internalTexture = rtt.getInternalTexture();
  96339. if (internalTexture) {
  96340. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96341. engine.unBindFramebuffer(internalTexture);
  96342. rtt.disposeFramebufferObjects();
  96343. passPostProcess.dispose();
  96344. internalTexture.isReady = true;
  96345. }
  96346. });
  96347. return rtt;
  96348. };
  96349. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96350. if (!scene._environmentBRDFTexture) {
  96351. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96352. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96353. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96354. scene._environmentBRDFTexture = texture;
  96355. }
  96356. return scene._environmentBRDFTexture;
  96357. };
  96358. 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=";
  96359. return TextureTools;
  96360. }());
  96361. BABYLON.TextureTools = TextureTools;
  96362. })(BABYLON || (BABYLON = {}));
  96363. //# sourceMappingURL=babylon.textureTools.js.map
  96364. var BABYLON;
  96365. (function (BABYLON) {
  96366. var FramingBehavior = /** @class */ (function () {
  96367. function FramingBehavior() {
  96368. this._mode = FramingBehavior.FitFrustumSidesMode;
  96369. this._radiusScale = 1.0;
  96370. this._positionScale = 0.5;
  96371. this._defaultElevation = 0.3;
  96372. this._elevationReturnTime = 1500;
  96373. this._elevationReturnWaitTime = 1000;
  96374. this._zoomStopsAnimation = false;
  96375. this._framingTime = 1500;
  96376. this._isPointerDown = false;
  96377. this._lastInteractionTime = -Infinity;
  96378. // Framing control
  96379. this._animatables = new Array();
  96380. this._betaIsAnimating = false;
  96381. }
  96382. Object.defineProperty(FramingBehavior.prototype, "name", {
  96383. get: function () {
  96384. return "Framing";
  96385. },
  96386. enumerable: true,
  96387. configurable: true
  96388. });
  96389. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96390. /**
  96391. * Gets current mode used by the behavior.
  96392. */
  96393. get: function () {
  96394. return this._mode;
  96395. },
  96396. /**
  96397. * Sets the current mode used by the behavior
  96398. */
  96399. set: function (mode) {
  96400. this._mode = mode;
  96401. },
  96402. enumerable: true,
  96403. configurable: true
  96404. });
  96405. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96406. /**
  96407. * Gets the scale applied to the radius
  96408. */
  96409. get: function () {
  96410. return this._radiusScale;
  96411. },
  96412. /**
  96413. * Sets the scale applied to the radius (1 by default)
  96414. */
  96415. set: function (radius) {
  96416. this._radiusScale = radius;
  96417. },
  96418. enumerable: true,
  96419. configurable: true
  96420. });
  96421. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96422. /**
  96423. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96424. */
  96425. get: function () {
  96426. return this._positionScale;
  96427. },
  96428. /**
  96429. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96430. */
  96431. set: function (scale) {
  96432. this._positionScale = scale;
  96433. },
  96434. enumerable: true,
  96435. configurable: true
  96436. });
  96437. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96438. /**
  96439. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96440. * behaviour is triggered, in radians.
  96441. */
  96442. get: function () {
  96443. return this._defaultElevation;
  96444. },
  96445. /**
  96446. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96447. * behaviour is triggered, in radians.
  96448. */
  96449. set: function (elevation) {
  96450. this._defaultElevation = elevation;
  96451. },
  96452. enumerable: true,
  96453. configurable: true
  96454. });
  96455. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96456. /**
  96457. * Gets the time (in milliseconds) taken to return to the default beta position.
  96458. * Negative value indicates camera should not return to default.
  96459. */
  96460. get: function () {
  96461. return this._elevationReturnTime;
  96462. },
  96463. /**
  96464. * Sets the time (in milliseconds) taken to return to the default beta position.
  96465. * Negative value indicates camera should not return to default.
  96466. */
  96467. set: function (speed) {
  96468. this._elevationReturnTime = speed;
  96469. },
  96470. enumerable: true,
  96471. configurable: true
  96472. });
  96473. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96474. /**
  96475. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96476. */
  96477. get: function () {
  96478. return this._elevationReturnWaitTime;
  96479. },
  96480. /**
  96481. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96482. */
  96483. set: function (time) {
  96484. this._elevationReturnWaitTime = time;
  96485. },
  96486. enumerable: true,
  96487. configurable: true
  96488. });
  96489. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96490. /**
  96491. * Gets the flag that indicates if user zooming should stop animation.
  96492. */
  96493. get: function () {
  96494. return this._zoomStopsAnimation;
  96495. },
  96496. /**
  96497. * Sets the flag that indicates if user zooming should stop animation.
  96498. */
  96499. set: function (flag) {
  96500. this._zoomStopsAnimation = flag;
  96501. },
  96502. enumerable: true,
  96503. configurable: true
  96504. });
  96505. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96506. /**
  96507. * Gets the transition time when framing the mesh, in milliseconds
  96508. */
  96509. get: function () {
  96510. return this._framingTime;
  96511. },
  96512. /**
  96513. * Sets the transition time when framing the mesh, in milliseconds
  96514. */
  96515. set: function (time) {
  96516. this._framingTime = time;
  96517. },
  96518. enumerable: true,
  96519. configurable: true
  96520. });
  96521. FramingBehavior.prototype.init = function () {
  96522. // Do notihng
  96523. };
  96524. FramingBehavior.prototype.attach = function (camera) {
  96525. var _this = this;
  96526. this._attachedCamera = camera;
  96527. var scene = this._attachedCamera.getScene();
  96528. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96529. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96530. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96531. _this._isPointerDown = true;
  96532. return;
  96533. }
  96534. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96535. _this._isPointerDown = false;
  96536. }
  96537. });
  96538. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96539. if (mesh) {
  96540. _this.zoomOnMesh(mesh);
  96541. }
  96542. });
  96543. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96544. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96545. _this._applyUserInteraction();
  96546. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96547. // back to the default position after a given timeout
  96548. _this._maintainCameraAboveGround();
  96549. });
  96550. };
  96551. FramingBehavior.prototype.detach = function () {
  96552. if (!this._attachedCamera) {
  96553. return;
  96554. }
  96555. var scene = this._attachedCamera.getScene();
  96556. if (this._onPrePointerObservableObserver) {
  96557. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96558. }
  96559. if (this._onAfterCheckInputsObserver) {
  96560. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96561. }
  96562. if (this._onMeshTargetChangedObserver) {
  96563. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96564. }
  96565. this._attachedCamera = null;
  96566. };
  96567. /**
  96568. * Targets the given mesh and updates zoom level accordingly.
  96569. * @param mesh The mesh to target.
  96570. * @param radius Optional. If a cached radius position already exists, overrides default.
  96571. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96572. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96573. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96574. */
  96575. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96576. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96577. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96578. mesh.computeWorldMatrix(true);
  96579. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96580. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96581. };
  96582. /**
  96583. * Targets the given mesh with its children and updates zoom level accordingly.
  96584. * @param mesh The mesh to target.
  96585. * @param radius Optional. If a cached radius position already exists, overrides default.
  96586. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96587. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96588. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96589. */
  96590. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96591. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96592. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96593. mesh.computeWorldMatrix(true);
  96594. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96595. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96596. };
  96597. /**
  96598. * Targets the given meshes with their children and updates zoom level accordingly.
  96599. * @param meshes The mesh to target.
  96600. * @param radius Optional. If a cached radius position already exists, overrides default.
  96601. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96602. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96603. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96604. */
  96605. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96606. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96607. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96608. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96609. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96610. for (var i = 0; i < meshes.length; i++) {
  96611. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96612. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96613. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96614. }
  96615. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96616. };
  96617. /**
  96618. * Targets the given mesh and updates zoom level accordingly.
  96619. * @param mesh The mesh to target.
  96620. * @param radius Optional. If a cached radius position already exists, overrides default.
  96621. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96622. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96623. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96624. */
  96625. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96626. var _this = this;
  96627. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96628. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96629. var zoomTarget;
  96630. if (!this._attachedCamera) {
  96631. return;
  96632. }
  96633. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96634. var bottom = minimumWorld.y;
  96635. var top = maximumWorld.y;
  96636. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96637. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96638. if (focusOnOriginXZ) {
  96639. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96640. }
  96641. else {
  96642. var centerWorld = minimumWorld.add(radiusWorld);
  96643. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96644. }
  96645. if (!this._vectorTransition) {
  96646. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  96647. }
  96648. this._betaIsAnimating = true;
  96649. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  96650. if (animatable) {
  96651. this._animatables.push(animatable);
  96652. }
  96653. // sets the radius and lower radius bounds
  96654. // Small delta ensures camera is not always at lower zoom limit.
  96655. var radius = 0;
  96656. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  96657. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96658. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  96659. radius = position;
  96660. }
  96661. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96662. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96663. if (this._attachedCamera.lowerRadiusLimit === null) {
  96664. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  96665. }
  96666. }
  96667. // Set sensibilities
  96668. var extend = maximumWorld.subtract(minimumWorld).length();
  96669. this._attachedCamera.panningSensibility = 5000 / extend;
  96670. this._attachedCamera.wheelPrecision = 100 / radius;
  96671. // transition to new radius
  96672. if (!this._radiusTransition) {
  96673. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96674. }
  96675. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  96676. _this.stopAllAnimations();
  96677. if (onAnimationEnd) {
  96678. onAnimationEnd();
  96679. }
  96680. if (_this._attachedCamera) {
  96681. _this._attachedCamera.storeState();
  96682. }
  96683. });
  96684. if (animatable) {
  96685. this._animatables.push(animatable);
  96686. }
  96687. };
  96688. /**
  96689. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96690. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96691. * frustum width.
  96692. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96693. * to fully enclose the mesh in the viewing frustum.
  96694. */
  96695. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96696. var size = maximumWorld.subtract(minimumWorld);
  96697. var boxVectorGlobalDiagonal = size.length();
  96698. var frustumSlope = this._getFrustumSlope();
  96699. // Formula for setting distance
  96700. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96701. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96702. // Horizon distance
  96703. var radius = radiusWithoutFraming * this._radiusScale;
  96704. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96705. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96706. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96707. var camera = this._attachedCamera;
  96708. if (!camera) {
  96709. return 0;
  96710. }
  96711. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96712. // Don't exceed the requested limit
  96713. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96714. }
  96715. // Don't exceed the upper radius limit
  96716. if (camera.upperRadiusLimit) {
  96717. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96718. }
  96719. return distance;
  96720. };
  96721. /**
  96722. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96723. * is automatically returned to its default position (expected to be above ground plane).
  96724. */
  96725. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96726. var _this = this;
  96727. if (this._elevationReturnTime < 0) {
  96728. return;
  96729. }
  96730. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96731. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96732. var limitBeta = Math.PI * 0.5;
  96733. // Bring the camera back up if below the ground plane
  96734. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96735. this._betaIsAnimating = true;
  96736. //Transition to new position
  96737. this.stopAllAnimations();
  96738. if (!this._betaTransition) {
  96739. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96740. }
  96741. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96742. _this._clearAnimationLocks();
  96743. _this.stopAllAnimations();
  96744. });
  96745. if (animatabe) {
  96746. this._animatables.push(animatabe);
  96747. }
  96748. }
  96749. };
  96750. /**
  96751. * Returns the frustum slope based on the canvas ratio and camera FOV
  96752. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96753. */
  96754. FramingBehavior.prototype._getFrustumSlope = function () {
  96755. // Calculate the viewport ratio
  96756. // Aspect Ratio is Height/Width.
  96757. var camera = this._attachedCamera;
  96758. if (!camera) {
  96759. return BABYLON.Vector2.Zero();
  96760. }
  96761. var engine = camera.getScene().getEngine();
  96762. var aspectRatio = engine.getAspectRatio(camera);
  96763. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96764. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96765. var frustumSlopeY = Math.tan(camera.fov / 2);
  96766. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96767. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96768. // along the forward vector.
  96769. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96770. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96771. };
  96772. /**
  96773. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96774. */
  96775. FramingBehavior.prototype._clearAnimationLocks = function () {
  96776. this._betaIsAnimating = false;
  96777. };
  96778. /**
  96779. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96780. */
  96781. FramingBehavior.prototype._applyUserInteraction = function () {
  96782. if (this.isUserIsMoving) {
  96783. this._lastInteractionTime = BABYLON.Tools.Now;
  96784. this.stopAllAnimations();
  96785. this._clearAnimationLocks();
  96786. }
  96787. };
  96788. /**
  96789. * Stops and removes all animations that have been applied to the camera
  96790. */
  96791. FramingBehavior.prototype.stopAllAnimations = function () {
  96792. if (this._attachedCamera) {
  96793. this._attachedCamera.animations = [];
  96794. }
  96795. while (this._animatables.length) {
  96796. if (this._animatables[0]) {
  96797. this._animatables[0].onAnimationEnd = null;
  96798. this._animatables[0].stop();
  96799. }
  96800. this._animatables.shift();
  96801. }
  96802. };
  96803. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96804. /**
  96805. * Gets a value indicating if the user is moving the camera
  96806. */
  96807. get: function () {
  96808. if (!this._attachedCamera) {
  96809. return false;
  96810. }
  96811. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96812. this._attachedCamera.inertialBetaOffset !== 0 ||
  96813. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96814. this._attachedCamera.inertialPanningX !== 0 ||
  96815. this._attachedCamera.inertialPanningY !== 0 ||
  96816. this._isPointerDown;
  96817. },
  96818. enumerable: true,
  96819. configurable: true
  96820. });
  96821. /**
  96822. * The easing function used by animations
  96823. */
  96824. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96825. /**
  96826. * The easing mode used by animations
  96827. */
  96828. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96829. // Statics
  96830. /**
  96831. * The camera can move all the way towards the mesh.
  96832. */
  96833. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96834. /**
  96835. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96836. */
  96837. FramingBehavior.FitFrustumSidesMode = 1;
  96838. return FramingBehavior;
  96839. }());
  96840. BABYLON.FramingBehavior = FramingBehavior;
  96841. })(BABYLON || (BABYLON = {}));
  96842. //# sourceMappingURL=babylon.framingBehavior.js.map
  96843. var BABYLON;
  96844. (function (BABYLON) {
  96845. /**
  96846. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  96847. */
  96848. var BouncingBehavior = /** @class */ (function () {
  96849. function BouncingBehavior() {
  96850. /**
  96851. * The duration of the animation, in milliseconds
  96852. */
  96853. this.transitionDuration = 450;
  96854. /**
  96855. * Length of the distance animated by the transition when lower radius is reached
  96856. */
  96857. this.lowerRadiusTransitionRange = 2;
  96858. /**
  96859. * Length of the distance animated by the transition when upper radius is reached
  96860. */
  96861. this.upperRadiusTransitionRange = -2;
  96862. this._autoTransitionRange = false;
  96863. // Animations
  96864. this._radiusIsAnimating = false;
  96865. this._radiusBounceTransition = null;
  96866. this._animatables = new Array();
  96867. }
  96868. Object.defineProperty(BouncingBehavior.prototype, "name", {
  96869. get: function () {
  96870. return "Bouncing";
  96871. },
  96872. enumerable: true,
  96873. configurable: true
  96874. });
  96875. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  96876. /**
  96877. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96878. */
  96879. get: function () {
  96880. return this._autoTransitionRange;
  96881. },
  96882. /**
  96883. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96884. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  96885. */
  96886. set: function (value) {
  96887. var _this = this;
  96888. if (this._autoTransitionRange === value) {
  96889. return;
  96890. }
  96891. this._autoTransitionRange = value;
  96892. var camera = this._attachedCamera;
  96893. if (!camera) {
  96894. return;
  96895. }
  96896. if (value) {
  96897. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96898. if (!mesh) {
  96899. return;
  96900. }
  96901. mesh.computeWorldMatrix(true);
  96902. var diagonal = mesh.getBoundingInfo().diagonalLength;
  96903. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  96904. _this.upperRadiusTransitionRange = diagonal * 0.05;
  96905. });
  96906. }
  96907. else if (this._onMeshTargetChangedObserver) {
  96908. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96909. }
  96910. },
  96911. enumerable: true,
  96912. configurable: true
  96913. });
  96914. BouncingBehavior.prototype.init = function () {
  96915. // Do notihng
  96916. };
  96917. BouncingBehavior.prototype.attach = function (camera) {
  96918. var _this = this;
  96919. this._attachedCamera = camera;
  96920. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96921. if (!_this._attachedCamera) {
  96922. return;
  96923. }
  96924. // Add the bounce animation to the lower radius limit
  96925. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  96926. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  96927. }
  96928. // Add the bounce animation to the upper radius limit
  96929. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  96930. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  96931. }
  96932. });
  96933. };
  96934. BouncingBehavior.prototype.detach = function () {
  96935. if (!this._attachedCamera) {
  96936. return;
  96937. }
  96938. if (this._onAfterCheckInputsObserver) {
  96939. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96940. }
  96941. if (this._onMeshTargetChangedObserver) {
  96942. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96943. }
  96944. this._attachedCamera = null;
  96945. };
  96946. /**
  96947. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  96948. * @param radiusLimit The limit to check against.
  96949. * @return Bool to indicate if at limit.
  96950. */
  96951. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  96952. if (!this._attachedCamera) {
  96953. return false;
  96954. }
  96955. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  96956. return true;
  96957. }
  96958. return false;
  96959. };
  96960. /**
  96961. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  96962. * @param radiusDelta The delta by which to animate to. Can be negative.
  96963. */
  96964. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  96965. var _this = this;
  96966. if (!this._attachedCamera) {
  96967. return;
  96968. }
  96969. if (!this._radiusBounceTransition) {
  96970. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  96971. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  96972. }
  96973. // Prevent zoom until bounce has completed
  96974. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  96975. this._attachedCamera.wheelPrecision = Infinity;
  96976. this._attachedCamera.inertialRadiusOffset = 0;
  96977. // Animate to the radius limit
  96978. this.stopAllAnimations();
  96979. this._radiusIsAnimating = true;
  96980. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  96981. if (animatable) {
  96982. this._animatables.push(animatable);
  96983. }
  96984. };
  96985. /**
  96986. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  96987. */
  96988. BouncingBehavior.prototype._clearAnimationLocks = function () {
  96989. this._radiusIsAnimating = false;
  96990. if (this._attachedCamera) {
  96991. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  96992. }
  96993. };
  96994. /**
  96995. * Stops and removes all animations that have been applied to the camera
  96996. */
  96997. BouncingBehavior.prototype.stopAllAnimations = function () {
  96998. if (this._attachedCamera) {
  96999. this._attachedCamera.animations = [];
  97000. }
  97001. while (this._animatables.length) {
  97002. this._animatables[0].onAnimationEnd = null;
  97003. this._animatables[0].stop();
  97004. this._animatables.shift();
  97005. }
  97006. };
  97007. /**
  97008. * The easing function used by animations
  97009. */
  97010. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  97011. /**
  97012. * The easing mode used by animations
  97013. */
  97014. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  97015. return BouncingBehavior;
  97016. }());
  97017. BABYLON.BouncingBehavior = BouncingBehavior;
  97018. })(BABYLON || (BABYLON = {}));
  97019. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  97020. var BABYLON;
  97021. (function (BABYLON) {
  97022. var AutoRotationBehavior = /** @class */ (function () {
  97023. function AutoRotationBehavior() {
  97024. this._zoomStopsAnimation = false;
  97025. this._idleRotationSpeed = 0.05;
  97026. this._idleRotationWaitTime = 2000;
  97027. this._idleRotationSpinupTime = 2000;
  97028. this._isPointerDown = false;
  97029. this._lastFrameTime = null;
  97030. this._lastInteractionTime = -Infinity;
  97031. this._cameraRotationSpeed = 0;
  97032. this._lastFrameRadius = 0;
  97033. }
  97034. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97035. get: function () {
  97036. return "AutoRotation";
  97037. },
  97038. enumerable: true,
  97039. configurable: true
  97040. });
  97041. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97042. /**
  97043. * Gets the flag that indicates if user zooming should stop animation.
  97044. */
  97045. get: function () {
  97046. return this._zoomStopsAnimation;
  97047. },
  97048. /**
  97049. * Sets the flag that indicates if user zooming should stop animation.
  97050. */
  97051. set: function (flag) {
  97052. this._zoomStopsAnimation = flag;
  97053. },
  97054. enumerable: true,
  97055. configurable: true
  97056. });
  97057. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97058. /**
  97059. * Gets the default speed at which the camera rotates around the model.
  97060. */
  97061. get: function () {
  97062. return this._idleRotationSpeed;
  97063. },
  97064. /**
  97065. * Sets the default speed at which the camera rotates around the model.
  97066. */
  97067. set: function (speed) {
  97068. this._idleRotationSpeed = speed;
  97069. },
  97070. enumerable: true,
  97071. configurable: true
  97072. });
  97073. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97074. /**
  97075. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97076. */
  97077. get: function () {
  97078. return this._idleRotationWaitTime;
  97079. },
  97080. /**
  97081. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97082. */
  97083. set: function (time) {
  97084. this._idleRotationWaitTime = time;
  97085. },
  97086. enumerable: true,
  97087. configurable: true
  97088. });
  97089. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97090. /**
  97091. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97092. */
  97093. get: function () {
  97094. return this._idleRotationSpinupTime;
  97095. },
  97096. /**
  97097. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97098. */
  97099. set: function (time) {
  97100. this._idleRotationSpinupTime = time;
  97101. },
  97102. enumerable: true,
  97103. configurable: true
  97104. });
  97105. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97106. /**
  97107. * Gets a value indicating if the camera is currently rotating because of this behavior
  97108. */
  97109. get: function () {
  97110. return Math.abs(this._cameraRotationSpeed) > 0;
  97111. },
  97112. enumerable: true,
  97113. configurable: true
  97114. });
  97115. AutoRotationBehavior.prototype.init = function () {
  97116. // Do notihng
  97117. };
  97118. AutoRotationBehavior.prototype.attach = function (camera) {
  97119. var _this = this;
  97120. this._attachedCamera = camera;
  97121. var scene = this._attachedCamera.getScene();
  97122. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97123. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97124. _this._isPointerDown = true;
  97125. return;
  97126. }
  97127. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97128. _this._isPointerDown = false;
  97129. }
  97130. });
  97131. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97132. var now = BABYLON.Tools.Now;
  97133. var dt = 0;
  97134. if (_this._lastFrameTime != null) {
  97135. dt = now - _this._lastFrameTime;
  97136. }
  97137. _this._lastFrameTime = now;
  97138. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97139. _this._applyUserInteraction();
  97140. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97141. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97142. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97143. // Step camera rotation by rotation speed
  97144. if (_this._attachedCamera) {
  97145. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97146. }
  97147. });
  97148. };
  97149. AutoRotationBehavior.prototype.detach = function () {
  97150. if (!this._attachedCamera) {
  97151. return;
  97152. }
  97153. var scene = this._attachedCamera.getScene();
  97154. if (this._onPrePointerObservableObserver) {
  97155. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97156. }
  97157. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97158. this._attachedCamera = null;
  97159. };
  97160. /**
  97161. * Returns true if user is scrolling.
  97162. * @return true if user is scrolling.
  97163. */
  97164. AutoRotationBehavior.prototype._userIsZooming = function () {
  97165. if (!this._attachedCamera) {
  97166. return false;
  97167. }
  97168. return this._attachedCamera.inertialRadiusOffset !== 0;
  97169. };
  97170. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97171. if (!this._attachedCamera) {
  97172. return false;
  97173. }
  97174. var zoomHasHitLimit = false;
  97175. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97176. zoomHasHitLimit = true;
  97177. }
  97178. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97179. this._lastFrameRadius = this._attachedCamera.radius;
  97180. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97181. };
  97182. /**
  97183. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97184. */
  97185. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97186. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97187. this._lastInteractionTime = BABYLON.Tools.Now;
  97188. }
  97189. };
  97190. // Tools
  97191. AutoRotationBehavior.prototype._userIsMoving = function () {
  97192. if (!this._attachedCamera) {
  97193. return false;
  97194. }
  97195. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97196. this._attachedCamera.inertialBetaOffset !== 0 ||
  97197. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97198. this._attachedCamera.inertialPanningX !== 0 ||
  97199. this._attachedCamera.inertialPanningY !== 0 ||
  97200. this._isPointerDown;
  97201. };
  97202. return AutoRotationBehavior;
  97203. }());
  97204. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97205. })(BABYLON || (BABYLON = {}));
  97206. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97207. var BABYLON;
  97208. (function (BABYLON) {
  97209. var NullEngineOptions = /** @class */ (function () {
  97210. function NullEngineOptions() {
  97211. this.renderWidth = 512;
  97212. this.renderHeight = 256;
  97213. this.textureSize = 512;
  97214. this.deterministicLockstep = false;
  97215. this.lockstepMaxSteps = 4;
  97216. }
  97217. return NullEngineOptions;
  97218. }());
  97219. BABYLON.NullEngineOptions = NullEngineOptions;
  97220. /**
  97221. * The null engine class provides support for headless version of babylon.js.
  97222. * This can be used in server side scenario or for testing purposes
  97223. */
  97224. var NullEngine = /** @class */ (function (_super) {
  97225. __extends(NullEngine, _super);
  97226. function NullEngine(options) {
  97227. if (options === void 0) { options = new NullEngineOptions(); }
  97228. var _this = _super.call(this, null) || this;
  97229. if (options.deterministicLockstep === undefined) {
  97230. options.deterministicLockstep = false;
  97231. }
  97232. if (options.lockstepMaxSteps === undefined) {
  97233. options.lockstepMaxSteps = 4;
  97234. }
  97235. _this._options = options;
  97236. // Init caps
  97237. // We consider we are on a webgl1 capable device
  97238. _this._caps = new BABYLON.EngineCapabilities();
  97239. _this._caps.maxTexturesImageUnits = 16;
  97240. _this._caps.maxVertexTextureImageUnits = 16;
  97241. _this._caps.maxTextureSize = 512;
  97242. _this._caps.maxCubemapTextureSize = 512;
  97243. _this._caps.maxRenderTextureSize = 512;
  97244. _this._caps.maxVertexAttribs = 16;
  97245. _this._caps.maxVaryingVectors = 16;
  97246. _this._caps.maxFragmentUniformVectors = 16;
  97247. _this._caps.maxVertexUniformVectors = 16;
  97248. // Extensions
  97249. _this._caps.standardDerivatives = false;
  97250. _this._caps.astc = null;
  97251. _this._caps.s3tc = null;
  97252. _this._caps.pvrtc = null;
  97253. _this._caps.etc1 = null;
  97254. _this._caps.etc2 = null;
  97255. _this._caps.textureAnisotropicFilterExtension = null;
  97256. _this._caps.maxAnisotropy = 0;
  97257. _this._caps.uintIndices = false;
  97258. _this._caps.fragmentDepthSupported = false;
  97259. _this._caps.highPrecisionShaderSupported = true;
  97260. _this._caps.colorBufferFloat = false;
  97261. _this._caps.textureFloat = false;
  97262. _this._caps.textureFloatLinearFiltering = false;
  97263. _this._caps.textureFloatRender = false;
  97264. _this._caps.textureHalfFloat = false;
  97265. _this._caps.textureHalfFloatLinearFiltering = false;
  97266. _this._caps.textureHalfFloatRender = false;
  97267. _this._caps.textureLOD = false;
  97268. _this._caps.drawBuffersExtension = false;
  97269. _this._caps.depthTextureExtension = false;
  97270. _this._caps.vertexArrayObject = false;
  97271. _this._caps.instancedArrays = false;
  97272. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97273. // Wrappers
  97274. if (typeof URL === "undefined") {
  97275. URL = {
  97276. createObjectURL: function () { },
  97277. revokeObjectURL: function () { }
  97278. };
  97279. }
  97280. if (typeof Blob === "undefined") {
  97281. Blob = function () { };
  97282. }
  97283. return _this;
  97284. }
  97285. NullEngine.prototype.isDeterministicLockStep = function () {
  97286. return this._options.deterministicLockstep;
  97287. };
  97288. NullEngine.prototype.getLockstepMaxSteps = function () {
  97289. return this._options.lockstepMaxSteps;
  97290. };
  97291. NullEngine.prototype.getHardwareScalingLevel = function () {
  97292. return 1.0;
  97293. };
  97294. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97295. return {
  97296. capacity: 0,
  97297. references: 1,
  97298. is32Bits: false
  97299. };
  97300. };
  97301. NullEngine.prototype.createIndexBuffer = function (indices) {
  97302. return {
  97303. capacity: 0,
  97304. references: 1,
  97305. is32Bits: false
  97306. };
  97307. };
  97308. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97309. if (stencil === void 0) { stencil = false; }
  97310. };
  97311. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97312. if (useScreen === void 0) { useScreen = false; }
  97313. if (!useScreen && this._currentRenderTarget) {
  97314. return this._currentRenderTarget.width;
  97315. }
  97316. return this._options.renderWidth;
  97317. };
  97318. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97319. if (useScreen === void 0) { useScreen = false; }
  97320. if (!useScreen && this._currentRenderTarget) {
  97321. return this._currentRenderTarget.height;
  97322. }
  97323. return this._options.renderHeight;
  97324. };
  97325. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97326. this._cachedViewport = viewport;
  97327. };
  97328. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97329. return {
  97330. transformFeedback: null,
  97331. __SPECTOR_rebuildProgram: null
  97332. };
  97333. };
  97334. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97335. return [];
  97336. };
  97337. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97338. return [];
  97339. };
  97340. NullEngine.prototype.bindSamplers = function (effect) {
  97341. this._currentEffect = null;
  97342. };
  97343. NullEngine.prototype.enableEffect = function (effect) {
  97344. this._currentEffect = effect;
  97345. if (effect.onBind) {
  97346. effect.onBind(effect);
  97347. }
  97348. effect.onBindObservable.notifyObservers(effect);
  97349. };
  97350. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97351. if (zOffset === void 0) { zOffset = 0; }
  97352. if (reverseSide === void 0) { reverseSide = false; }
  97353. };
  97354. NullEngine.prototype.setIntArray = function (uniform, array) {
  97355. };
  97356. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97357. };
  97358. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97359. };
  97360. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97361. };
  97362. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97363. };
  97364. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97365. };
  97366. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97367. };
  97368. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97369. };
  97370. NullEngine.prototype.setArray = function (uniform, array) {
  97371. };
  97372. NullEngine.prototype.setArray2 = function (uniform, array) {
  97373. };
  97374. NullEngine.prototype.setArray3 = function (uniform, array) {
  97375. };
  97376. NullEngine.prototype.setArray4 = function (uniform, array) {
  97377. };
  97378. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97379. };
  97380. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97381. };
  97382. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97383. };
  97384. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97385. };
  97386. NullEngine.prototype.setFloat = function (uniform, value) {
  97387. };
  97388. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97389. };
  97390. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97391. };
  97392. NullEngine.prototype.setBool = function (uniform, bool) {
  97393. };
  97394. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97395. };
  97396. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97397. };
  97398. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97399. };
  97400. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97401. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97402. if (this._alphaMode === mode) {
  97403. return;
  97404. }
  97405. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97406. if (!noDepthWriteChange) {
  97407. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97408. }
  97409. this._alphaMode = mode;
  97410. };
  97411. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97412. };
  97413. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97414. if (this.preventCacheWipeBetweenFrames) {
  97415. return;
  97416. }
  97417. this.resetTextureCache();
  97418. this._currentEffect = null;
  97419. if (bruteForce) {
  97420. this._currentProgram = null;
  97421. this._stencilState.reset();
  97422. this._depthCullingState.reset();
  97423. this._alphaState.reset();
  97424. }
  97425. this._cachedVertexBuffers = null;
  97426. this._cachedIndexBuffer = null;
  97427. this._cachedEffectForVertexBuffers = null;
  97428. };
  97429. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97430. };
  97431. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97432. };
  97433. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97434. };
  97435. NullEngine.prototype._createTexture = function () {
  97436. return {};
  97437. };
  97438. NullEngine.prototype._releaseTexture = function (texture) {
  97439. };
  97440. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97442. if (onLoad === void 0) { onLoad = null; }
  97443. if (onError === void 0) { onError = null; }
  97444. if (buffer === void 0) { buffer = null; }
  97445. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97446. var url = String(urlArg);
  97447. texture.url = url;
  97448. texture.generateMipMaps = !noMipmap;
  97449. texture.samplingMode = samplingMode;
  97450. texture.invertY = invertY;
  97451. texture.baseWidth = this._options.textureSize;
  97452. texture.baseHeight = this._options.textureSize;
  97453. texture.width = this._options.textureSize;
  97454. texture.height = this._options.textureSize;
  97455. if (format) {
  97456. texture.format = format;
  97457. }
  97458. texture.isReady = true;
  97459. if (onLoad) {
  97460. onLoad();
  97461. }
  97462. this._internalTexturesCache.push(texture);
  97463. return texture;
  97464. };
  97465. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97466. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97467. if (options !== undefined && typeof options === "object") {
  97468. fullOptions.generateMipMaps = options.generateMipMaps;
  97469. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97470. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97471. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97472. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97473. }
  97474. else {
  97475. fullOptions.generateMipMaps = options;
  97476. fullOptions.generateDepthBuffer = true;
  97477. fullOptions.generateStencilBuffer = false;
  97478. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97479. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97480. }
  97481. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97482. var width = size.width || size;
  97483. var height = size.height || size;
  97484. texture._depthStencilBuffer = {};
  97485. texture._framebuffer = {};
  97486. texture.baseWidth = width;
  97487. texture.baseHeight = height;
  97488. texture.width = width;
  97489. texture.height = height;
  97490. texture.isReady = true;
  97491. texture.samples = 1;
  97492. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97493. texture.samplingMode = fullOptions.samplingMode;
  97494. texture.type = fullOptions.type;
  97495. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97496. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97497. this._internalTexturesCache.push(texture);
  97498. return texture;
  97499. };
  97500. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97501. texture.samplingMode = samplingMode;
  97502. };
  97503. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97504. if (this._currentRenderTarget) {
  97505. this.unBindFramebuffer(this._currentRenderTarget);
  97506. }
  97507. this._currentRenderTarget = texture;
  97508. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97509. if (this._cachedViewport && !forceFullscreenViewport) {
  97510. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97511. }
  97512. };
  97513. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97514. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97515. this._currentRenderTarget = null;
  97516. if (onBeforeUnbind) {
  97517. if (texture._MSAAFramebuffer) {
  97518. this._currentFramebuffer = texture._framebuffer;
  97519. }
  97520. onBeforeUnbind();
  97521. }
  97522. this._currentFramebuffer = null;
  97523. };
  97524. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97525. var vbo = {
  97526. capacity: 1,
  97527. references: 1,
  97528. is32Bits: false
  97529. };
  97530. return vbo;
  97531. };
  97532. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97533. if (offset === void 0) { offset = 0; }
  97534. };
  97535. /**
  97536. * Updates a dynamic vertex buffer.
  97537. * @param vertexBuffer the vertex buffer to update
  97538. * @param data the data used to update the vertex buffer
  97539. * @param byteOffset the byte offset of the data (optional)
  97540. * @param byteLength the byte length of the data (optional)
  97541. */
  97542. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97543. };
  97544. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97545. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97546. this._boundTexturesCache[this._activeChannel] = texture;
  97547. }
  97548. };
  97549. NullEngine.prototype._bindTexture = function (channel, texture) {
  97550. if (channel < 0) {
  97551. return;
  97552. }
  97553. this._bindTextureDirectly(0, texture);
  97554. };
  97555. NullEngine.prototype._releaseBuffer = function (buffer) {
  97556. buffer.references--;
  97557. if (buffer.references === 0) {
  97558. return true;
  97559. }
  97560. return false;
  97561. };
  97562. NullEngine.prototype.releaseEffects = function () {
  97563. };
  97564. return NullEngine;
  97565. }(BABYLON.Engine));
  97566. BABYLON.NullEngine = NullEngine;
  97567. })(BABYLON || (BABYLON = {}));
  97568. //# sourceMappingURL=babylon.nullEngine.js.map
  97569. var BABYLON;
  97570. (function (BABYLON) {
  97571. /**
  97572. * This class can be used to get instrumentation data from a Babylon engine
  97573. */
  97574. var EngineInstrumentation = /** @class */ (function () {
  97575. function EngineInstrumentation(engine) {
  97576. this.engine = engine;
  97577. this._captureGPUFrameTime = false;
  97578. this._gpuFrameTime = new BABYLON.PerfCounter();
  97579. this._captureShaderCompilationTime = false;
  97580. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97581. // Observers
  97582. this._onBeginFrameObserver = null;
  97583. this._onEndFrameObserver = null;
  97584. this._onBeforeShaderCompilationObserver = null;
  97585. this._onAfterShaderCompilationObserver = null;
  97586. }
  97587. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97588. // Properties
  97589. /**
  97590. * Gets the perf counter used for GPU frame time
  97591. */
  97592. get: function () {
  97593. return this._gpuFrameTime;
  97594. },
  97595. enumerable: true,
  97596. configurable: true
  97597. });
  97598. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97599. /**
  97600. * Gets the GPU frame time capture status
  97601. */
  97602. get: function () {
  97603. return this._captureGPUFrameTime;
  97604. },
  97605. /**
  97606. * Enable or disable the GPU frame time capture
  97607. */
  97608. set: function (value) {
  97609. var _this = this;
  97610. if (value === this._captureGPUFrameTime) {
  97611. return;
  97612. }
  97613. this._captureGPUFrameTime = value;
  97614. if (value) {
  97615. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97616. if (!_this._gpuFrameTimeToken) {
  97617. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97618. }
  97619. });
  97620. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97621. if (!_this._gpuFrameTimeToken) {
  97622. return;
  97623. }
  97624. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97625. if (time > -1) {
  97626. _this._gpuFrameTimeToken = null;
  97627. _this._gpuFrameTime.fetchNewFrame();
  97628. _this._gpuFrameTime.addCount(time, true);
  97629. }
  97630. });
  97631. }
  97632. else {
  97633. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97634. this._onBeginFrameObserver = null;
  97635. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97636. this._onEndFrameObserver = null;
  97637. }
  97638. },
  97639. enumerable: true,
  97640. configurable: true
  97641. });
  97642. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97643. /**
  97644. * Gets the perf counter used for shader compilation time
  97645. */
  97646. get: function () {
  97647. return this._shaderCompilationTime;
  97648. },
  97649. enumerable: true,
  97650. configurable: true
  97651. });
  97652. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  97653. /**
  97654. * Gets the shader compilation time capture status
  97655. */
  97656. get: function () {
  97657. return this._captureShaderCompilationTime;
  97658. },
  97659. /**
  97660. * Enable or disable the shader compilation time capture
  97661. */
  97662. set: function (value) {
  97663. var _this = this;
  97664. if (value === this._captureShaderCompilationTime) {
  97665. return;
  97666. }
  97667. this._captureShaderCompilationTime = value;
  97668. if (value) {
  97669. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  97670. _this._shaderCompilationTime.fetchNewFrame();
  97671. _this._shaderCompilationTime.beginMonitoring();
  97672. });
  97673. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  97674. _this._shaderCompilationTime.endMonitoring();
  97675. });
  97676. }
  97677. else {
  97678. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97679. this._onBeforeShaderCompilationObserver = null;
  97680. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97681. this._onAfterShaderCompilationObserver = null;
  97682. }
  97683. },
  97684. enumerable: true,
  97685. configurable: true
  97686. });
  97687. EngineInstrumentation.prototype.dispose = function () {
  97688. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97689. this._onBeginFrameObserver = null;
  97690. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97691. this._onEndFrameObserver = null;
  97692. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97693. this._onBeforeShaderCompilationObserver = null;
  97694. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97695. this._onAfterShaderCompilationObserver = null;
  97696. this.engine = null;
  97697. };
  97698. return EngineInstrumentation;
  97699. }());
  97700. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97701. })(BABYLON || (BABYLON = {}));
  97702. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97703. var BABYLON;
  97704. (function (BABYLON) {
  97705. /**
  97706. * This class can be used to get instrumentation data from a Babylon engine
  97707. */
  97708. var SceneInstrumentation = /** @class */ (function () {
  97709. function SceneInstrumentation(scene) {
  97710. var _this = this;
  97711. this.scene = scene;
  97712. this._captureActiveMeshesEvaluationTime = false;
  97713. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97714. this._captureRenderTargetsRenderTime = false;
  97715. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97716. this._captureFrameTime = false;
  97717. this._frameTime = new BABYLON.PerfCounter();
  97718. this._captureRenderTime = false;
  97719. this._renderTime = new BABYLON.PerfCounter();
  97720. this._captureInterFrameTime = false;
  97721. this._interFrameTime = new BABYLON.PerfCounter();
  97722. this._captureParticlesRenderTime = false;
  97723. this._particlesRenderTime = new BABYLON.PerfCounter();
  97724. this._captureSpritesRenderTime = false;
  97725. this._spritesRenderTime = new BABYLON.PerfCounter();
  97726. this._capturePhysicsTime = false;
  97727. this._physicsTime = new BABYLON.PerfCounter();
  97728. this._captureAnimationsTime = false;
  97729. this._animationsTime = new BABYLON.PerfCounter();
  97730. // Observers
  97731. this._onBeforeActiveMeshesEvaluationObserver = null;
  97732. this._onAfterActiveMeshesEvaluationObserver = null;
  97733. this._onBeforeRenderTargetsRenderObserver = null;
  97734. this._onAfterRenderTargetsRenderObserver = null;
  97735. this._onAfterRenderObserver = null;
  97736. this._onBeforeDrawPhaseObserver = null;
  97737. this._onAfterDrawPhaseObserver = null;
  97738. this._onBeforeAnimationsObserver = null;
  97739. this._onBeforeParticlesRenderingObserver = null;
  97740. this._onAfterParticlesRenderingObserver = null;
  97741. this._onBeforeSpritesRenderingObserver = null;
  97742. this._onAfterSpritesRenderingObserver = null;
  97743. this._onBeforePhysicsObserver = null;
  97744. this._onAfterPhysicsObserver = null;
  97745. this._onAfterAnimationsObserver = null;
  97746. // Before render
  97747. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97748. if (_this._captureActiveMeshesEvaluationTime) {
  97749. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97750. }
  97751. if (_this._captureRenderTargetsRenderTime) {
  97752. _this._renderTargetsRenderTime.fetchNewFrame();
  97753. }
  97754. if (_this._captureFrameTime) {
  97755. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97756. _this._frameTime.beginMonitoring();
  97757. }
  97758. if (_this._captureInterFrameTime) {
  97759. _this._interFrameTime.endMonitoring();
  97760. }
  97761. if (_this._captureParticlesRenderTime) {
  97762. _this._particlesRenderTime.fetchNewFrame();
  97763. }
  97764. if (_this._captureSpritesRenderTime) {
  97765. _this._spritesRenderTime.fetchNewFrame();
  97766. }
  97767. if (_this._captureAnimationsTime) {
  97768. _this._animationsTime.beginMonitoring();
  97769. }
  97770. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97771. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97772. });
  97773. // After render
  97774. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97775. if (_this._captureFrameTime) {
  97776. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97777. _this._frameTime.endMonitoring();
  97778. }
  97779. if (_this._captureRenderTime) {
  97780. _this._renderTime.endMonitoring(false);
  97781. }
  97782. if (_this._captureInterFrameTime) {
  97783. _this._interFrameTime.beginMonitoring();
  97784. }
  97785. });
  97786. }
  97787. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97788. // Properties
  97789. /**
  97790. * Gets the perf counter used for active meshes evaluation time
  97791. */
  97792. get: function () {
  97793. return this._activeMeshesEvaluationTime;
  97794. },
  97795. enumerable: true,
  97796. configurable: true
  97797. });
  97798. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97799. /**
  97800. * Gets the active meshes evaluation time capture status
  97801. */
  97802. get: function () {
  97803. return this._captureActiveMeshesEvaluationTime;
  97804. },
  97805. /**
  97806. * Enable or disable the active meshes evaluation time capture
  97807. */
  97808. set: function (value) {
  97809. var _this = this;
  97810. if (value === this._captureActiveMeshesEvaluationTime) {
  97811. return;
  97812. }
  97813. this._captureActiveMeshesEvaluationTime = value;
  97814. if (value) {
  97815. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97816. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97817. _this._activeMeshesEvaluationTime.beginMonitoring();
  97818. });
  97819. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97820. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97821. _this._activeMeshesEvaluationTime.endMonitoring();
  97822. });
  97823. }
  97824. else {
  97825. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97826. this._onBeforeActiveMeshesEvaluationObserver = null;
  97827. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97828. this._onAfterActiveMeshesEvaluationObserver = null;
  97829. }
  97830. },
  97831. enumerable: true,
  97832. configurable: true
  97833. });
  97834. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97835. /**
  97836. * Gets the perf counter used for render targets render time
  97837. */
  97838. get: function () {
  97839. return this._renderTargetsRenderTime;
  97840. },
  97841. enumerable: true,
  97842. configurable: true
  97843. });
  97844. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  97845. /**
  97846. * Gets the render targets render time capture status
  97847. */
  97848. get: function () {
  97849. return this._captureRenderTargetsRenderTime;
  97850. },
  97851. /**
  97852. * Enable or disable the render targets render time capture
  97853. */
  97854. set: function (value) {
  97855. var _this = this;
  97856. if (value === this._captureRenderTargetsRenderTime) {
  97857. return;
  97858. }
  97859. this._captureRenderTargetsRenderTime = value;
  97860. if (value) {
  97861. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  97862. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  97863. _this._renderTargetsRenderTime.beginMonitoring();
  97864. });
  97865. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  97866. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  97867. _this._renderTargetsRenderTime.endMonitoring(false);
  97868. });
  97869. }
  97870. else {
  97871. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97872. this._onBeforeRenderTargetsRenderObserver = null;
  97873. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97874. this._onAfterRenderTargetsRenderObserver = null;
  97875. }
  97876. },
  97877. enumerable: true,
  97878. configurable: true
  97879. });
  97880. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  97881. /**
  97882. * Gets the perf counter used for particles render time
  97883. */
  97884. get: function () {
  97885. return this._particlesRenderTime;
  97886. },
  97887. enumerable: true,
  97888. configurable: true
  97889. });
  97890. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  97891. /**
  97892. * Gets the particles render time capture status
  97893. */
  97894. get: function () {
  97895. return this._captureParticlesRenderTime;
  97896. },
  97897. /**
  97898. * Enable or disable the particles render time capture
  97899. */
  97900. set: function (value) {
  97901. var _this = this;
  97902. if (value === this._captureParticlesRenderTime) {
  97903. return;
  97904. }
  97905. this._captureParticlesRenderTime = value;
  97906. if (value) {
  97907. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  97908. BABYLON.Tools.StartPerformanceCounter("Particles");
  97909. _this._particlesRenderTime.beginMonitoring();
  97910. });
  97911. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  97912. BABYLON.Tools.EndPerformanceCounter("Particles");
  97913. _this._particlesRenderTime.endMonitoring(false);
  97914. });
  97915. }
  97916. else {
  97917. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97918. this._onBeforeParticlesRenderingObserver = null;
  97919. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97920. this._onAfterParticlesRenderingObserver = null;
  97921. }
  97922. },
  97923. enumerable: true,
  97924. configurable: true
  97925. });
  97926. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  97927. /**
  97928. * Gets the perf counter used for sprites render time
  97929. */
  97930. get: function () {
  97931. return this._spritesRenderTime;
  97932. },
  97933. enumerable: true,
  97934. configurable: true
  97935. });
  97936. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  97937. /**
  97938. * Gets the sprites render time capture status
  97939. */
  97940. get: function () {
  97941. return this._captureSpritesRenderTime;
  97942. },
  97943. /**
  97944. * Enable or disable the sprites render time capture
  97945. */
  97946. set: function (value) {
  97947. var _this = this;
  97948. if (value === this._captureSpritesRenderTime) {
  97949. return;
  97950. }
  97951. this._captureSpritesRenderTime = value;
  97952. if (value) {
  97953. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  97954. BABYLON.Tools.StartPerformanceCounter("Sprites");
  97955. _this._spritesRenderTime.beginMonitoring();
  97956. });
  97957. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  97958. BABYLON.Tools.EndPerformanceCounter("Sprites");
  97959. _this._spritesRenderTime.endMonitoring(false);
  97960. });
  97961. }
  97962. else {
  97963. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97964. this._onBeforeSpritesRenderingObserver = null;
  97965. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97966. this._onAfterSpritesRenderingObserver = null;
  97967. }
  97968. },
  97969. enumerable: true,
  97970. configurable: true
  97971. });
  97972. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  97973. /**
  97974. * Gets the perf counter used for physics time
  97975. */
  97976. get: function () {
  97977. return this._physicsTime;
  97978. },
  97979. enumerable: true,
  97980. configurable: true
  97981. });
  97982. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  97983. /**
  97984. * Gets the physics time capture status
  97985. */
  97986. get: function () {
  97987. return this._capturePhysicsTime;
  97988. },
  97989. /**
  97990. * Enable or disable the physics time capture
  97991. */
  97992. set: function (value) {
  97993. var _this = this;
  97994. if (value === this._capturePhysicsTime) {
  97995. return;
  97996. }
  97997. this._capturePhysicsTime = value;
  97998. if (value) {
  97999. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  98000. BABYLON.Tools.StartPerformanceCounter("Physics");
  98001. _this._physicsTime.beginMonitoring();
  98002. });
  98003. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  98004. BABYLON.Tools.EndPerformanceCounter("Physics");
  98005. _this._physicsTime.endMonitoring();
  98006. });
  98007. }
  98008. else {
  98009. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98010. this._onBeforePhysicsObserver = null;
  98011. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98012. this._onAfterPhysicsObserver = null;
  98013. }
  98014. },
  98015. enumerable: true,
  98016. configurable: true
  98017. });
  98018. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  98019. /**
  98020. * Gets the perf counter used for animations time
  98021. */
  98022. get: function () {
  98023. return this._animationsTime;
  98024. },
  98025. enumerable: true,
  98026. configurable: true
  98027. });
  98028. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  98029. /**
  98030. * Gets the animations time capture status
  98031. */
  98032. get: function () {
  98033. return this._captureAnimationsTime;
  98034. },
  98035. /**
  98036. * Enable or disable the animations time capture
  98037. */
  98038. set: function (value) {
  98039. var _this = this;
  98040. if (value === this._captureAnimationsTime) {
  98041. return;
  98042. }
  98043. this._captureAnimationsTime = value;
  98044. if (value) {
  98045. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98046. _this._animationsTime.endMonitoring();
  98047. });
  98048. }
  98049. else {
  98050. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98051. this._onAfterAnimationsObserver = null;
  98052. }
  98053. },
  98054. enumerable: true,
  98055. configurable: true
  98056. });
  98057. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98058. /**
  98059. * Gets the perf counter used for frame time capture
  98060. */
  98061. get: function () {
  98062. return this._frameTime;
  98063. },
  98064. enumerable: true,
  98065. configurable: true
  98066. });
  98067. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98068. /**
  98069. * Gets the frame time capture status
  98070. */
  98071. get: function () {
  98072. return this._captureFrameTime;
  98073. },
  98074. /**
  98075. * Enable or disable the frame time capture
  98076. */
  98077. set: function (value) {
  98078. this._captureFrameTime = value;
  98079. },
  98080. enumerable: true,
  98081. configurable: true
  98082. });
  98083. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98084. /**
  98085. * Gets the perf counter used for inter-frames time capture
  98086. */
  98087. get: function () {
  98088. return this._interFrameTime;
  98089. },
  98090. enumerable: true,
  98091. configurable: true
  98092. });
  98093. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98094. /**
  98095. * Gets the inter-frames time capture status
  98096. */
  98097. get: function () {
  98098. return this._captureInterFrameTime;
  98099. },
  98100. /**
  98101. * Enable or disable the inter-frames time capture
  98102. */
  98103. set: function (value) {
  98104. this._captureInterFrameTime = value;
  98105. },
  98106. enumerable: true,
  98107. configurable: true
  98108. });
  98109. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98110. /**
  98111. * Gets the perf counter used for render time capture
  98112. */
  98113. get: function () {
  98114. return this._renderTime;
  98115. },
  98116. enumerable: true,
  98117. configurable: true
  98118. });
  98119. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98120. /**
  98121. * Gets the render time capture status
  98122. */
  98123. get: function () {
  98124. return this._captureRenderTime;
  98125. },
  98126. /**
  98127. * Enable or disable the render time capture
  98128. */
  98129. set: function (value) {
  98130. var _this = this;
  98131. if (value === this._captureRenderTime) {
  98132. return;
  98133. }
  98134. this._captureRenderTime = value;
  98135. if (value) {
  98136. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98137. _this._renderTime.beginMonitoring();
  98138. BABYLON.Tools.StartPerformanceCounter("Main render");
  98139. });
  98140. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98141. _this._renderTime.endMonitoring(false);
  98142. BABYLON.Tools.EndPerformanceCounter("Main render");
  98143. });
  98144. }
  98145. else {
  98146. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98147. this._onBeforeDrawPhaseObserver = null;
  98148. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98149. this._onAfterDrawPhaseObserver = null;
  98150. }
  98151. },
  98152. enumerable: true,
  98153. configurable: true
  98154. });
  98155. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98156. /**
  98157. * Gets the perf counter used for draw calls
  98158. */
  98159. get: function () {
  98160. return this.scene.getEngine()._drawCalls;
  98161. },
  98162. enumerable: true,
  98163. configurable: true
  98164. });
  98165. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98166. /**
  98167. * Gets the perf counter used for texture collisions
  98168. */
  98169. get: function () {
  98170. return this.scene.getEngine()._textureCollisions;
  98171. },
  98172. enumerable: true,
  98173. configurable: true
  98174. });
  98175. SceneInstrumentation.prototype.dispose = function () {
  98176. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98177. this._onAfterRenderObserver = null;
  98178. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98179. this._onBeforeActiveMeshesEvaluationObserver = null;
  98180. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98181. this._onAfterActiveMeshesEvaluationObserver = null;
  98182. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98183. this._onBeforeRenderTargetsRenderObserver = null;
  98184. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98185. this._onAfterRenderTargetsRenderObserver = null;
  98186. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98187. this._onBeforeAnimationsObserver = null;
  98188. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98189. this._onBeforeParticlesRenderingObserver = null;
  98190. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98191. this._onAfterParticlesRenderingObserver = null;
  98192. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98193. this._onBeforeSpritesRenderingObserver = null;
  98194. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98195. this._onAfterSpritesRenderingObserver = null;
  98196. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98197. this._onBeforeDrawPhaseObserver = null;
  98198. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98199. this._onAfterDrawPhaseObserver = null;
  98200. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98201. this._onBeforePhysicsObserver = null;
  98202. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98203. this._onAfterPhysicsObserver = null;
  98204. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98205. this._onAfterAnimationsObserver = null;
  98206. this.scene = null;
  98207. };
  98208. return SceneInstrumentation;
  98209. }());
  98210. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98211. })(BABYLON || (BABYLON = {}));
  98212. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98213. var BABYLON;
  98214. (function (BABYLON) {
  98215. /**
  98216. * @hidden
  98217. **/
  98218. var _TimeToken = /** @class */ (function () {
  98219. function _TimeToken() {
  98220. this._timeElapsedQueryEnded = false;
  98221. }
  98222. return _TimeToken;
  98223. }());
  98224. BABYLON._TimeToken = _TimeToken;
  98225. })(BABYLON || (BABYLON = {}));
  98226. //# sourceMappingURL=babylon.timeToken.js.map
  98227. var BABYLON;
  98228. (function (BABYLON) {
  98229. /**
  98230. * Background material defines definition.
  98231. * @hidden Mainly internal Use
  98232. */
  98233. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98234. __extends(BackgroundMaterialDefines, _super);
  98235. /**
  98236. * Constructor of the defines.
  98237. */
  98238. function BackgroundMaterialDefines() {
  98239. var _this = _super.call(this) || this;
  98240. /**
  98241. * True if the diffuse texture is in use.
  98242. */
  98243. _this.DIFFUSE = false;
  98244. /**
  98245. * The direct UV channel to use.
  98246. */
  98247. _this.DIFFUSEDIRECTUV = 0;
  98248. /**
  98249. * True if the diffuse texture is in gamma space.
  98250. */
  98251. _this.GAMMADIFFUSE = false;
  98252. /**
  98253. * True if the diffuse texture has opacity in the alpha channel.
  98254. */
  98255. _this.DIFFUSEHASALPHA = false;
  98256. /**
  98257. * True if you want the material to fade to transparent at grazing angle.
  98258. */
  98259. _this.OPACITYFRESNEL = false;
  98260. /**
  98261. * True if an extra blur needs to be added in the reflection.
  98262. */
  98263. _this.REFLECTIONBLUR = false;
  98264. /**
  98265. * True if you want the material to fade to reflection at grazing angle.
  98266. */
  98267. _this.REFLECTIONFRESNEL = false;
  98268. /**
  98269. * True if you want the material to falloff as far as you move away from the scene center.
  98270. */
  98271. _this.REFLECTIONFALLOFF = false;
  98272. /**
  98273. * False if the current Webgl implementation does not support the texture lod extension.
  98274. */
  98275. _this.TEXTURELODSUPPORT = false;
  98276. /**
  98277. * True to ensure the data are premultiplied.
  98278. */
  98279. _this.PREMULTIPLYALPHA = false;
  98280. /**
  98281. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98282. */
  98283. _this.USERGBCOLOR = false;
  98284. /**
  98285. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98286. * stays aligned with the desired configuration.
  98287. */
  98288. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98289. /**
  98290. * True to add noise in order to reduce the banding effect.
  98291. */
  98292. _this.NOISE = false;
  98293. /**
  98294. * is the reflection texture in BGR color scheme?
  98295. * Mainly used to solve a bug in ios10 video tag
  98296. */
  98297. _this.REFLECTIONBGR = false;
  98298. _this.IMAGEPROCESSING = false;
  98299. _this.VIGNETTE = false;
  98300. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98301. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98302. _this.TONEMAPPING = false;
  98303. _this.CONTRAST = false;
  98304. _this.COLORCURVES = false;
  98305. _this.COLORGRADING = false;
  98306. _this.COLORGRADING3D = false;
  98307. _this.SAMPLER3DGREENDEPTH = false;
  98308. _this.SAMPLER3DBGRMAP = false;
  98309. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98310. _this.EXPOSURE = false;
  98311. // Reflection.
  98312. _this.REFLECTION = false;
  98313. _this.REFLECTIONMAP_3D = false;
  98314. _this.REFLECTIONMAP_SPHERICAL = false;
  98315. _this.REFLECTIONMAP_PLANAR = false;
  98316. _this.REFLECTIONMAP_CUBIC = false;
  98317. _this.REFLECTIONMAP_PROJECTION = false;
  98318. _this.REFLECTIONMAP_SKYBOX = false;
  98319. _this.REFLECTIONMAP_EXPLICIT = false;
  98320. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98321. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98322. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98323. _this.INVERTCUBICMAP = false;
  98324. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98325. _this.LODINREFLECTIONALPHA = false;
  98326. _this.GAMMAREFLECTION = false;
  98327. _this.RGBDREFLECTION = false;
  98328. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98329. // Default BJS.
  98330. _this.MAINUV1 = false;
  98331. _this.MAINUV2 = false;
  98332. _this.UV1 = false;
  98333. _this.UV2 = false;
  98334. _this.CLIPPLANE = false;
  98335. _this.POINTSIZE = false;
  98336. _this.FOG = false;
  98337. _this.NORMAL = false;
  98338. _this.NUM_BONE_INFLUENCERS = 0;
  98339. _this.BonesPerMesh = 0;
  98340. _this.INSTANCES = false;
  98341. _this.SHADOWFLOAT = false;
  98342. _this.rebuild();
  98343. return _this;
  98344. }
  98345. return BackgroundMaterialDefines;
  98346. }(BABYLON.MaterialDefines));
  98347. /**
  98348. * Background material used to create an efficient environement around your scene.
  98349. */
  98350. var BackgroundMaterial = /** @class */ (function (_super) {
  98351. __extends(BackgroundMaterial, _super);
  98352. /**
  98353. * Instantiates a Background Material in the given scene
  98354. * @param name The friendly name of the material
  98355. * @param scene The scene to add the material to
  98356. */
  98357. function BackgroundMaterial(name, scene) {
  98358. var _this = _super.call(this, name, scene) || this;
  98359. /**
  98360. * Key light Color (multiply against the environement texture)
  98361. */
  98362. _this.primaryColor = BABYLON.Color3.White();
  98363. _this._primaryColorShadowLevel = 0;
  98364. _this._primaryColorHighlightLevel = 0;
  98365. /**
  98366. * Reflection Texture used in the material.
  98367. * Should be author in a specific way for the best result (refer to the documentation).
  98368. */
  98369. _this.reflectionTexture = null;
  98370. /**
  98371. * Reflection Texture level of blur.
  98372. *
  98373. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98374. * texture twice.
  98375. */
  98376. _this.reflectionBlur = 0;
  98377. /**
  98378. * Diffuse Texture used in the material.
  98379. * Should be author in a specific way for the best result (refer to the documentation).
  98380. */
  98381. _this.diffuseTexture = null;
  98382. _this._shadowLights = null;
  98383. /**
  98384. * Specify the list of lights casting shadow on the material.
  98385. * All scene shadow lights will be included if null.
  98386. */
  98387. _this.shadowLights = null;
  98388. /**
  98389. * Helps adjusting the shadow to a softer level if required.
  98390. * 0 means black shadows and 1 means no shadows.
  98391. */
  98392. _this.shadowLevel = 0;
  98393. /**
  98394. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98395. * It is usually zero but might be interesting to modify according to your setup.
  98396. */
  98397. _this.sceneCenter = BABYLON.Vector3.Zero();
  98398. /**
  98399. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98400. * This helps ensuring a nice transition when the camera goes under the ground.
  98401. */
  98402. _this.opacityFresnel = true;
  98403. /**
  98404. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98405. * This helps adding a mirror texture on the ground.
  98406. */
  98407. _this.reflectionFresnel = false;
  98408. /**
  98409. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98410. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98411. */
  98412. _this.reflectionFalloffDistance = 0.0;
  98413. /**
  98414. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98415. */
  98416. _this.reflectionAmount = 1.0;
  98417. /**
  98418. * This specifies the weight of the reflection at grazing angle.
  98419. */
  98420. _this.reflectionReflectance0 = 0.05;
  98421. /**
  98422. * This specifies the weight of the reflection at a perpendicular point of view.
  98423. */
  98424. _this.reflectionReflectance90 = 0.5;
  98425. /**
  98426. * Helps to directly use the maps channels instead of their level.
  98427. */
  98428. _this.useRGBColor = true;
  98429. /**
  98430. * This helps reducing the banding effect that could occur on the background.
  98431. */
  98432. _this.enableNoise = false;
  98433. _this._fovMultiplier = 1.0;
  98434. /**
  98435. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98436. */
  98437. _this.useEquirectangularFOV = false;
  98438. _this._maxSimultaneousLights = 4;
  98439. /**
  98440. * Number of Simultaneous lights allowed on the material.
  98441. */
  98442. _this.maxSimultaneousLights = 4;
  98443. /**
  98444. * Keep track of the image processing observer to allow dispose and replace.
  98445. */
  98446. _this._imageProcessingObserver = null;
  98447. /**
  98448. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98449. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98450. */
  98451. _this.switchToBGR = false;
  98452. // Temp values kept as cache in the material.
  98453. _this._renderTargets = new BABYLON.SmartArray(16);
  98454. _this._reflectionControls = BABYLON.Vector4.Zero();
  98455. _this._white = BABYLON.Color3.White();
  98456. _this._primaryShadowColor = BABYLON.Color3.Black();
  98457. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98458. // Setup the default processing configuration to the scene.
  98459. _this._attachImageProcessingConfiguration(null);
  98460. _this.getRenderTargetTextures = function () {
  98461. _this._renderTargets.reset();
  98462. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98463. _this._renderTargets.push(_this._diffuseTexture);
  98464. }
  98465. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98466. _this._renderTargets.push(_this._reflectionTexture);
  98467. }
  98468. return _this._renderTargets;
  98469. };
  98470. return _this;
  98471. }
  98472. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98473. /**
  98474. * Experimental Internal Use Only.
  98475. *
  98476. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98477. * This acts as a helper to set the primary color to a more "human friendly" value.
  98478. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98479. * output color as close as possible from the chosen value.
  98480. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98481. * part of lighting setup.)
  98482. */
  98483. get: function () {
  98484. return this.__perceptualColor;
  98485. },
  98486. set: function (value) {
  98487. this.__perceptualColor = value;
  98488. this._computePrimaryColorFromPerceptualColor();
  98489. this._markAllSubMeshesAsLightsDirty();
  98490. },
  98491. enumerable: true,
  98492. configurable: true
  98493. });
  98494. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98495. /**
  98496. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98497. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98498. */
  98499. get: function () {
  98500. return this._primaryColorShadowLevel;
  98501. },
  98502. set: function (value) {
  98503. this._primaryColorShadowLevel = value;
  98504. this._computePrimaryColors();
  98505. this._markAllSubMeshesAsLightsDirty();
  98506. },
  98507. enumerable: true,
  98508. configurable: true
  98509. });
  98510. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98511. /**
  98512. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98513. * The primary color is used at the level chosen to define what the white area would look.
  98514. */
  98515. get: function () {
  98516. return this._primaryColorHighlightLevel;
  98517. },
  98518. set: function (value) {
  98519. this._primaryColorHighlightLevel = value;
  98520. this._computePrimaryColors();
  98521. this._markAllSubMeshesAsLightsDirty();
  98522. },
  98523. enumerable: true,
  98524. configurable: true
  98525. });
  98526. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98527. /**
  98528. * Sets the reflection reflectance fresnel values according to the default standard
  98529. * empirically know to work well :-)
  98530. */
  98531. set: function (value) {
  98532. var reflectionWeight = value;
  98533. if (reflectionWeight < 0.5) {
  98534. reflectionWeight = reflectionWeight * 2.0;
  98535. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98536. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98537. }
  98538. else {
  98539. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98540. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98541. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98542. }
  98543. },
  98544. enumerable: true,
  98545. configurable: true
  98546. });
  98547. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98548. /**
  98549. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98550. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98551. * Recommended to be keep at 1.0 except for special cases.
  98552. */
  98553. get: function () {
  98554. return this._fovMultiplier;
  98555. },
  98556. set: function (value) {
  98557. if (isNaN(value)) {
  98558. value = 1.0;
  98559. }
  98560. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98561. },
  98562. enumerable: true,
  98563. configurable: true
  98564. });
  98565. /**
  98566. * Attaches a new image processing configuration to the PBR Material.
  98567. * @param configuration (if null the scene configuration will be use)
  98568. */
  98569. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98570. var _this = this;
  98571. if (configuration === this._imageProcessingConfiguration) {
  98572. return;
  98573. }
  98574. // Detaches observer.
  98575. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98576. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98577. }
  98578. // Pick the scene configuration if needed.
  98579. if (!configuration) {
  98580. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98581. }
  98582. else {
  98583. this._imageProcessingConfiguration = configuration;
  98584. }
  98585. // Attaches observer.
  98586. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98587. _this._computePrimaryColorFromPerceptualColor();
  98588. _this._markAllSubMeshesAsImageProcessingDirty();
  98589. });
  98590. };
  98591. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98592. /**
  98593. * Gets the image processing configuration used either in this material.
  98594. */
  98595. get: function () {
  98596. return this._imageProcessingConfiguration;
  98597. },
  98598. /**
  98599. * Sets the Default image processing configuration used either in the this material.
  98600. *
  98601. * If sets to null, the scene one is in use.
  98602. */
  98603. set: function (value) {
  98604. this._attachImageProcessingConfiguration(value);
  98605. // Ensure the effect will be rebuilt.
  98606. this._markAllSubMeshesAsTexturesDirty();
  98607. },
  98608. enumerable: true,
  98609. configurable: true
  98610. });
  98611. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98612. /**
  98613. * Gets wether the color curves effect is enabled.
  98614. */
  98615. get: function () {
  98616. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98617. },
  98618. /**
  98619. * Sets wether the color curves effect is enabled.
  98620. */
  98621. set: function (value) {
  98622. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98623. },
  98624. enumerable: true,
  98625. configurable: true
  98626. });
  98627. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98628. /**
  98629. * Gets wether the color grading effect is enabled.
  98630. */
  98631. get: function () {
  98632. return this.imageProcessingConfiguration.colorGradingEnabled;
  98633. },
  98634. /**
  98635. * Gets wether the color grading effect is enabled.
  98636. */
  98637. set: function (value) {
  98638. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98639. },
  98640. enumerable: true,
  98641. configurable: true
  98642. });
  98643. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  98644. /**
  98645. * Gets wether tonemapping is enabled or not.
  98646. */
  98647. get: function () {
  98648. return this._imageProcessingConfiguration.toneMappingEnabled;
  98649. },
  98650. /**
  98651. * Sets wether tonemapping is enabled or not
  98652. */
  98653. set: function (value) {
  98654. this._imageProcessingConfiguration.toneMappingEnabled = value;
  98655. },
  98656. enumerable: true,
  98657. configurable: true
  98658. });
  98659. ;
  98660. ;
  98661. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  98662. /**
  98663. * The camera exposure used on this material.
  98664. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98665. * This corresponds to a photographic exposure.
  98666. */
  98667. get: function () {
  98668. return this._imageProcessingConfiguration.exposure;
  98669. },
  98670. /**
  98671. * The camera exposure used on this material.
  98672. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98673. * This corresponds to a photographic exposure.
  98674. */
  98675. set: function (value) {
  98676. this._imageProcessingConfiguration.exposure = value;
  98677. },
  98678. enumerable: true,
  98679. configurable: true
  98680. });
  98681. ;
  98682. ;
  98683. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98684. /**
  98685. * Gets The camera contrast used on this material.
  98686. */
  98687. get: function () {
  98688. return this._imageProcessingConfiguration.contrast;
  98689. },
  98690. /**
  98691. * Sets The camera contrast used on this material.
  98692. */
  98693. set: function (value) {
  98694. this._imageProcessingConfiguration.contrast = value;
  98695. },
  98696. enumerable: true,
  98697. configurable: true
  98698. });
  98699. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98700. /**
  98701. * Gets the Color Grading 2D Lookup Texture.
  98702. */
  98703. get: function () {
  98704. return this._imageProcessingConfiguration.colorGradingTexture;
  98705. },
  98706. /**
  98707. * Sets the Color Grading 2D Lookup Texture.
  98708. */
  98709. set: function (value) {
  98710. this.imageProcessingConfiguration.colorGradingTexture = value;
  98711. },
  98712. enumerable: true,
  98713. configurable: true
  98714. });
  98715. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98716. /**
  98717. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98718. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98719. * 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;
  98720. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98721. */
  98722. get: function () {
  98723. return this.imageProcessingConfiguration.colorCurves;
  98724. },
  98725. /**
  98726. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98727. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98728. * 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;
  98729. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98730. */
  98731. set: function (value) {
  98732. this.imageProcessingConfiguration.colorCurves = value;
  98733. },
  98734. enumerable: true,
  98735. configurable: true
  98736. });
  98737. /**
  98738. * The entire material has been created in order to prevent overdraw.
  98739. * @returns false
  98740. */
  98741. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98742. return true;
  98743. };
  98744. /**
  98745. * The entire material has been created in order to prevent overdraw.
  98746. * @returns true if blending is enable
  98747. */
  98748. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98749. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98750. };
  98751. /**
  98752. * Checks wether the material is ready to be rendered for a given mesh.
  98753. * @param mesh The mesh to render
  98754. * @param subMesh The submesh to check against
  98755. * @param useInstances Specify wether or not the material is used with instances
  98756. * @returns true if all the dependencies are ready (Textures, Effects...)
  98757. */
  98758. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98759. var _this = this;
  98760. if (useInstances === void 0) { useInstances = false; }
  98761. if (subMesh.effect && this.isFrozen) {
  98762. if (this._wasPreviouslyReady) {
  98763. return true;
  98764. }
  98765. }
  98766. if (!subMesh._materialDefines) {
  98767. subMesh._materialDefines = new BackgroundMaterialDefines();
  98768. }
  98769. var scene = this.getScene();
  98770. var defines = subMesh._materialDefines;
  98771. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98772. if (defines._renderId === scene.getRenderId()) {
  98773. return true;
  98774. }
  98775. }
  98776. var engine = scene.getEngine();
  98777. // Lights
  98778. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98779. defines._needNormals = true;
  98780. // Textures
  98781. if (defines._areTexturesDirty) {
  98782. defines._needUVs = false;
  98783. if (scene.texturesEnabled) {
  98784. if (scene.getEngine().getCaps().textureLOD) {
  98785. defines.TEXTURELODSUPPORT = true;
  98786. }
  98787. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98788. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98789. return false;
  98790. }
  98791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98792. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98793. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98794. defines.OPACITYFRESNEL = this._opacityFresnel;
  98795. }
  98796. else {
  98797. defines.DIFFUSE = false;
  98798. defines.DIFFUSEHASALPHA = false;
  98799. defines.GAMMADIFFUSE = false;
  98800. defines.OPACITYFRESNEL = false;
  98801. }
  98802. var reflectionTexture = this._reflectionTexture;
  98803. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98804. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98805. return false;
  98806. }
  98807. defines.REFLECTION = true;
  98808. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98809. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  98810. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98811. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98812. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98813. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98814. defines.REFLECTIONBGR = this.switchToBGR;
  98815. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98816. defines.INVERTCUBICMAP = true;
  98817. }
  98818. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98819. switch (reflectionTexture.coordinatesMode) {
  98820. case BABYLON.Texture.EXPLICIT_MODE:
  98821. defines.REFLECTIONMAP_EXPLICIT = true;
  98822. break;
  98823. case BABYLON.Texture.PLANAR_MODE:
  98824. defines.REFLECTIONMAP_PLANAR = true;
  98825. break;
  98826. case BABYLON.Texture.PROJECTION_MODE:
  98827. defines.REFLECTIONMAP_PROJECTION = true;
  98828. break;
  98829. case BABYLON.Texture.SKYBOX_MODE:
  98830. defines.REFLECTIONMAP_SKYBOX = true;
  98831. break;
  98832. case BABYLON.Texture.SPHERICAL_MODE:
  98833. defines.REFLECTIONMAP_SPHERICAL = true;
  98834. break;
  98835. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98836. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98837. break;
  98838. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98839. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98840. break;
  98841. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98842. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  98843. break;
  98844. case BABYLON.Texture.CUBIC_MODE:
  98845. case BABYLON.Texture.INVCUBIC_MODE:
  98846. default:
  98847. defines.REFLECTIONMAP_CUBIC = true;
  98848. break;
  98849. }
  98850. if (this.reflectionFresnel) {
  98851. defines.REFLECTIONFRESNEL = true;
  98852. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  98853. this._reflectionControls.x = this.reflectionAmount;
  98854. this._reflectionControls.y = this.reflectionReflectance0;
  98855. this._reflectionControls.z = this.reflectionReflectance90;
  98856. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  98857. }
  98858. else {
  98859. defines.REFLECTIONFRESNEL = false;
  98860. defines.REFLECTIONFALLOFF = false;
  98861. }
  98862. }
  98863. else {
  98864. defines.REFLECTION = false;
  98865. defines.REFLECTIONFRESNEL = false;
  98866. defines.REFLECTIONFALLOFF = false;
  98867. defines.REFLECTIONBLUR = false;
  98868. defines.REFLECTIONMAP_3D = false;
  98869. defines.REFLECTIONMAP_SPHERICAL = false;
  98870. defines.REFLECTIONMAP_PLANAR = false;
  98871. defines.REFLECTIONMAP_CUBIC = false;
  98872. defines.REFLECTIONMAP_PROJECTION = false;
  98873. defines.REFLECTIONMAP_SKYBOX = false;
  98874. defines.REFLECTIONMAP_EXPLICIT = false;
  98875. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98876. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98877. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98878. defines.INVERTCUBICMAP = false;
  98879. defines.REFLECTIONMAP_OPPOSITEZ = false;
  98880. defines.LODINREFLECTIONALPHA = false;
  98881. defines.GAMMAREFLECTION = false;
  98882. defines.RGBDREFLECTION = false;
  98883. }
  98884. }
  98885. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  98886. defines.USERGBCOLOR = this._useRGBColor;
  98887. defines.NOISE = this._enableNoise;
  98888. }
  98889. if (defines._areLightsDirty) {
  98890. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  98891. }
  98892. if (defines._areImageProcessingDirty) {
  98893. if (!this._imageProcessingConfiguration.isReady()) {
  98894. return false;
  98895. }
  98896. this._imageProcessingConfiguration.prepareDefines(defines);
  98897. }
  98898. // Misc.
  98899. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  98900. // Values that need to be evaluated on every frame
  98901. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  98902. // Attribs
  98903. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  98904. if (mesh) {
  98905. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98906. mesh.createNormals(true);
  98907. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  98908. }
  98909. }
  98910. }
  98911. // Get correct effect
  98912. if (defines.isDirty) {
  98913. defines.markAsProcessed();
  98914. scene.resetCachedMaterial();
  98915. // Fallbacks
  98916. var fallbacks = new BABYLON.EffectFallbacks();
  98917. if (defines.FOG) {
  98918. fallbacks.addFallback(0, "FOG");
  98919. }
  98920. if (defines.POINTSIZE) {
  98921. fallbacks.addFallback(1, "POINTSIZE");
  98922. }
  98923. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  98924. if (defines.NUM_BONE_INFLUENCERS > 0) {
  98925. fallbacks.addCPUSkinningFallback(0, mesh);
  98926. }
  98927. //Attributes
  98928. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98929. if (defines.NORMAL) {
  98930. attribs.push(BABYLON.VertexBuffer.NormalKind);
  98931. }
  98932. if (defines.UV1) {
  98933. attribs.push(BABYLON.VertexBuffer.UVKind);
  98934. }
  98935. if (defines.UV2) {
  98936. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98937. }
  98938. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  98939. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  98940. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  98941. "vFogInfos", "vFogColor", "pointSize",
  98942. "vClipPlane", "mBones",
  98943. "vPrimaryColor", "vPrimaryColorShadow",
  98944. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  98945. "shadowLevel", "alpha",
  98946. "vBackgroundCenter", "vReflectionControl",
  98947. "vDiffuseInfos", "diffuseMatrix",
  98948. ];
  98949. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  98950. var uniformBuffers = ["Material", "Scene"];
  98951. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  98952. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  98953. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  98954. uniformsNames: uniforms,
  98955. uniformBuffersNames: uniformBuffers,
  98956. samplers: samplers,
  98957. defines: defines,
  98958. maxSimultaneousLights: this._maxSimultaneousLights
  98959. });
  98960. var onCompiled = function (effect) {
  98961. if (_this.onCompiled) {
  98962. _this.onCompiled(effect);
  98963. }
  98964. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  98965. };
  98966. var join = defines.toString();
  98967. subMesh.setEffect(scene.getEngine().createEffect("background", {
  98968. attributes: attribs,
  98969. uniformsNames: uniforms,
  98970. uniformBuffersNames: uniformBuffers,
  98971. samplers: samplers,
  98972. defines: join,
  98973. fallbacks: fallbacks,
  98974. onCompiled: onCompiled,
  98975. onError: this.onError,
  98976. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  98977. }, engine), defines);
  98978. this.buildUniformLayout();
  98979. }
  98980. if (!subMesh.effect || !subMesh.effect.isReady()) {
  98981. return false;
  98982. }
  98983. defines._renderId = scene.getRenderId();
  98984. this._wasPreviouslyReady = true;
  98985. return true;
  98986. };
  98987. /**
  98988. * Compute the primary color according to the chosen perceptual color.
  98989. */
  98990. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  98991. if (!this.__perceptualColor) {
  98992. return;
  98993. }
  98994. this._primaryColor.copyFrom(this.__perceptualColor);
  98995. // Revert gamma space.
  98996. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  98997. // Revert image processing configuration.
  98998. if (this._imageProcessingConfiguration) {
  98999. // Revert Exposure.
  99000. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  99001. }
  99002. this._computePrimaryColors();
  99003. };
  99004. /**
  99005. * Compute the highlights and shadow colors according to their chosen levels.
  99006. */
  99007. BackgroundMaterial.prototype._computePrimaryColors = function () {
  99008. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  99009. return;
  99010. }
  99011. // Find the highlight color based on the configuration.
  99012. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  99013. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  99014. // Find the shadow color based on the configuration.
  99015. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  99016. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  99017. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  99018. };
  99019. /**
  99020. * Build the uniform buffer used in the material.
  99021. */
  99022. BackgroundMaterial.prototype.buildUniformLayout = function () {
  99023. // Order is important !
  99024. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  99025. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  99026. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  99027. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  99028. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  99029. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  99030. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  99031. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  99032. this._uniformBuffer.addUniform("pointSize", 1);
  99033. this._uniformBuffer.addUniform("shadowLevel", 1);
  99034. this._uniformBuffer.addUniform("alpha", 1);
  99035. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99036. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99037. this._uniformBuffer.create();
  99038. };
  99039. /**
  99040. * Unbind the material.
  99041. */
  99042. BackgroundMaterial.prototype.unbind = function () {
  99043. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99044. this._uniformBuffer.setTexture("diffuseSampler", null);
  99045. }
  99046. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99047. this._uniformBuffer.setTexture("reflectionSampler", null);
  99048. }
  99049. _super.prototype.unbind.call(this);
  99050. };
  99051. /**
  99052. * Bind only the world matrix to the material.
  99053. * @param world The world matrix to bind.
  99054. */
  99055. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99056. this._activeEffect.setMatrix("world", world);
  99057. };
  99058. /**
  99059. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99060. * @param world The world matrix to bind.
  99061. * @param subMesh The submesh to bind for.
  99062. */
  99063. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99064. var scene = this.getScene();
  99065. var defines = subMesh._materialDefines;
  99066. if (!defines) {
  99067. return;
  99068. }
  99069. var effect = subMesh.effect;
  99070. if (!effect) {
  99071. return;
  99072. }
  99073. this._activeEffect = effect;
  99074. // Matrices
  99075. this.bindOnlyWorldMatrix(world);
  99076. // Bones
  99077. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99078. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99079. if (mustRebind) {
  99080. this._uniformBuffer.bindToEffect(effect, "Material");
  99081. this.bindViewProjection(effect);
  99082. var reflectionTexture = this._reflectionTexture;
  99083. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99084. // Texture uniforms
  99085. if (scene.texturesEnabled) {
  99086. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99087. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99088. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99089. }
  99090. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99091. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99092. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99093. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99094. }
  99095. }
  99096. if (this.shadowLevel > 0) {
  99097. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99098. }
  99099. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99100. // Point size
  99101. if (this.pointsCloud) {
  99102. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99103. }
  99104. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99105. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99106. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99107. }
  99108. else {
  99109. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99110. }
  99111. }
  99112. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99113. // Textures
  99114. if (scene.texturesEnabled) {
  99115. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99116. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99117. }
  99118. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99119. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99120. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99121. }
  99122. else if (!defines.REFLECTIONBLUR) {
  99123. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99124. }
  99125. else {
  99126. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99127. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99128. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99129. }
  99130. if (defines.REFLECTIONFRESNEL) {
  99131. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99132. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99133. }
  99134. }
  99135. }
  99136. // Clip plane
  99137. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99138. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99139. }
  99140. if (mustRebind || !this.isFrozen) {
  99141. if (scene.lightsEnabled) {
  99142. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99143. }
  99144. // View
  99145. this.bindView(effect);
  99146. // Fog
  99147. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99148. // image processing
  99149. this._imageProcessingConfiguration.bind(this._activeEffect);
  99150. }
  99151. this._uniformBuffer.update();
  99152. this._afterBind(mesh);
  99153. };
  99154. /**
  99155. * Dispose the material.
  99156. * @param forceDisposeEffect Force disposal of the associated effect.
  99157. * @param forceDisposeTextures Force disposal of the associated textures.
  99158. */
  99159. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99160. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99161. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99162. if (forceDisposeTextures) {
  99163. if (this.diffuseTexture) {
  99164. this.diffuseTexture.dispose();
  99165. }
  99166. if (this.reflectionTexture) {
  99167. this.reflectionTexture.dispose();
  99168. }
  99169. }
  99170. this._renderTargets.dispose();
  99171. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99172. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99173. }
  99174. _super.prototype.dispose.call(this, forceDisposeEffect);
  99175. };
  99176. /**
  99177. * Clones the material.
  99178. * @param name The cloned name.
  99179. * @returns The cloned material.
  99180. */
  99181. BackgroundMaterial.prototype.clone = function (name) {
  99182. var _this = this;
  99183. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99184. };
  99185. /**
  99186. * Serializes the current material to its JSON representation.
  99187. * @returns The JSON representation.
  99188. */
  99189. BackgroundMaterial.prototype.serialize = function () {
  99190. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99191. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99192. return serializationObject;
  99193. };
  99194. /**
  99195. * Gets the class name of the material
  99196. * @returns "BackgroundMaterial"
  99197. */
  99198. BackgroundMaterial.prototype.getClassName = function () {
  99199. return "BackgroundMaterial";
  99200. };
  99201. /**
  99202. * Parse a JSON input to create back a background material.
  99203. * @param source The JSON data to parse
  99204. * @param scene The scene to create the parsed material in
  99205. * @param rootUrl The root url of the assets the material depends upon
  99206. * @returns the instantiated BackgroundMaterial.
  99207. */
  99208. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99209. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99210. };
  99211. /**
  99212. * Standard reflectance value at parallel view angle.
  99213. */
  99214. BackgroundMaterial.StandardReflectance0 = 0.05;
  99215. /**
  99216. * Standard reflectance value at grazing angle.
  99217. */
  99218. BackgroundMaterial.StandardReflectance90 = 0.5;
  99219. __decorate([
  99220. BABYLON.serializeAsColor3()
  99221. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99222. __decorate([
  99223. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99224. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99225. __decorate([
  99226. BABYLON.serializeAsColor3()
  99227. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99228. __decorate([
  99229. BABYLON.serialize()
  99230. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99231. __decorate([
  99232. BABYLON.serialize()
  99233. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99234. __decorate([
  99235. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99236. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99237. __decorate([
  99238. BABYLON.serializeAsTexture()
  99239. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99240. __decorate([
  99241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99242. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99243. __decorate([
  99244. BABYLON.serialize()
  99245. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99246. __decorate([
  99247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99248. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99249. __decorate([
  99250. BABYLON.serializeAsTexture()
  99251. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99252. __decorate([
  99253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99254. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99255. __decorate([
  99256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99257. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99258. __decorate([
  99259. BABYLON.serialize()
  99260. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99261. __decorate([
  99262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99263. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99264. __decorate([
  99265. BABYLON.serializeAsVector3()
  99266. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99267. __decorate([
  99268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99269. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99270. __decorate([
  99271. BABYLON.serialize()
  99272. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99273. __decorate([
  99274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99275. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99276. __decorate([
  99277. BABYLON.serialize()
  99278. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99279. __decorate([
  99280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99281. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99282. __decorate([
  99283. BABYLON.serialize()
  99284. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99285. __decorate([
  99286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99287. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99288. __decorate([
  99289. BABYLON.serialize()
  99290. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99291. __decorate([
  99292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99293. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99294. __decorate([
  99295. BABYLON.serialize()
  99296. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99297. __decorate([
  99298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99299. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99300. __decorate([
  99301. BABYLON.serialize()
  99302. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99303. __decorate([
  99304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99305. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99306. __decorate([
  99307. BABYLON.serialize()
  99308. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99309. __decorate([
  99310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99311. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99312. __decorate([
  99313. BABYLON.serialize()
  99314. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99315. __decorate([
  99316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99317. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99318. __decorate([
  99319. BABYLON.serialize()
  99320. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99321. __decorate([
  99322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99323. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99324. __decorate([
  99325. BABYLON.serializeAsImageProcessingConfiguration()
  99326. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99327. return BackgroundMaterial;
  99328. }(BABYLON.PushMaterial));
  99329. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99330. })(BABYLON || (BABYLON = {}));
  99331. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99332. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99333. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99334. s = arguments[i];
  99335. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99336. t[p] = s[p];
  99337. }
  99338. return t;
  99339. };
  99340. var BABYLON;
  99341. (function (BABYLON) {
  99342. /**
  99343. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99344. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99345. * It also helps with the default setup of your imageProcessing configuration.
  99346. */
  99347. var EnvironmentHelper = /** @class */ (function () {
  99348. /**
  99349. * constructor
  99350. * @param options
  99351. * @param scene The scene to add the material to
  99352. */
  99353. function EnvironmentHelper(options, scene) {
  99354. var _this = this;
  99355. this._errorHandler = function (message, exception) {
  99356. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99357. };
  99358. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99359. this._scene = scene;
  99360. this.onErrorObservable = new BABYLON.Observable();
  99361. this._setupBackground();
  99362. this._setupImageProcessing();
  99363. }
  99364. /**
  99365. * Creates the default options for the helper.
  99366. */
  99367. EnvironmentHelper._getDefaultOptions = function () {
  99368. return {
  99369. createGround: true,
  99370. groundSize: 15,
  99371. groundTexture: this._groundTextureCDNUrl,
  99372. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99373. groundOpacity: 0.9,
  99374. enableGroundShadow: true,
  99375. groundShadowLevel: 0.5,
  99376. enableGroundMirror: false,
  99377. groundMirrorSizeRatio: 0.3,
  99378. groundMirrorBlurKernel: 64,
  99379. groundMirrorAmount: 1,
  99380. groundMirrorFresnelWeight: 1,
  99381. groundMirrorFallOffDistance: 0,
  99382. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99383. groundYBias: 0.00001,
  99384. createSkybox: true,
  99385. skyboxSize: 20,
  99386. skyboxTexture: this._skyboxTextureCDNUrl,
  99387. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99388. backgroundYRotation: 0,
  99389. sizeAuto: true,
  99390. rootPosition: BABYLON.Vector3.Zero(),
  99391. setupImageProcessing: true,
  99392. environmentTexture: this._environmentTextureCDNUrl,
  99393. cameraExposure: 0.8,
  99394. cameraContrast: 1.2,
  99395. toneMappingEnabled: true,
  99396. };
  99397. };
  99398. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99399. /**
  99400. * Gets the root mesh created by the helper.
  99401. */
  99402. get: function () {
  99403. return this._rootMesh;
  99404. },
  99405. enumerable: true,
  99406. configurable: true
  99407. });
  99408. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99409. /**
  99410. * Gets the skybox created by the helper.
  99411. */
  99412. get: function () {
  99413. return this._skybox;
  99414. },
  99415. enumerable: true,
  99416. configurable: true
  99417. });
  99418. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99419. /**
  99420. * Gets the skybox texture created by the helper.
  99421. */
  99422. get: function () {
  99423. return this._skyboxTexture;
  99424. },
  99425. enumerable: true,
  99426. configurable: true
  99427. });
  99428. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99429. /**
  99430. * Gets the skybox material created by the helper.
  99431. */
  99432. get: function () {
  99433. return this._skyboxMaterial;
  99434. },
  99435. enumerable: true,
  99436. configurable: true
  99437. });
  99438. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99439. /**
  99440. * Gets the ground mesh created by the helper.
  99441. */
  99442. get: function () {
  99443. return this._ground;
  99444. },
  99445. enumerable: true,
  99446. configurable: true
  99447. });
  99448. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99449. /**
  99450. * Gets the ground texture created by the helper.
  99451. */
  99452. get: function () {
  99453. return this._groundTexture;
  99454. },
  99455. enumerable: true,
  99456. configurable: true
  99457. });
  99458. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99459. /**
  99460. * Gets the ground mirror created by the helper.
  99461. */
  99462. get: function () {
  99463. return this._groundMirror;
  99464. },
  99465. enumerable: true,
  99466. configurable: true
  99467. });
  99468. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99469. /**
  99470. * Gets the ground mirror render list to helps pushing the meshes
  99471. * you wish in the ground reflection.
  99472. */
  99473. get: function () {
  99474. if (this._groundMirror) {
  99475. return this._groundMirror.renderList;
  99476. }
  99477. return null;
  99478. },
  99479. enumerable: true,
  99480. configurable: true
  99481. });
  99482. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99483. /**
  99484. * Gets the ground material created by the helper.
  99485. */
  99486. get: function () {
  99487. return this._groundMaterial;
  99488. },
  99489. enumerable: true,
  99490. configurable: true
  99491. });
  99492. /**
  99493. * Updates the background according to the new options
  99494. * @param options
  99495. */
  99496. EnvironmentHelper.prototype.updateOptions = function (options) {
  99497. var newOptions = __assign({}, this._options, options);
  99498. if (this._ground && !newOptions.createGround) {
  99499. this._ground.dispose();
  99500. this._ground = null;
  99501. }
  99502. if (this._groundMaterial && !newOptions.createGround) {
  99503. this._groundMaterial.dispose();
  99504. this._groundMaterial = null;
  99505. }
  99506. if (this._groundTexture) {
  99507. if (this._options.groundTexture != newOptions.groundTexture) {
  99508. this._groundTexture.dispose();
  99509. this._groundTexture = null;
  99510. }
  99511. }
  99512. if (this._skybox && !newOptions.createSkybox) {
  99513. this._skybox.dispose();
  99514. this._skybox = null;
  99515. }
  99516. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99517. this._skyboxMaterial.dispose();
  99518. this._skyboxMaterial = null;
  99519. }
  99520. if (this._skyboxTexture) {
  99521. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99522. this._skyboxTexture.dispose();
  99523. this._skyboxTexture = null;
  99524. }
  99525. }
  99526. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99527. this._groundMirror.dispose();
  99528. this._groundMirror = null;
  99529. }
  99530. if (this._scene.environmentTexture) {
  99531. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99532. this._scene.environmentTexture.dispose();
  99533. }
  99534. }
  99535. this._options = newOptions;
  99536. this._setupBackground();
  99537. this._setupImageProcessing();
  99538. };
  99539. /**
  99540. * Sets the primary color of all the available elements.
  99541. * @param color the main color to affect to the ground and the background
  99542. */
  99543. EnvironmentHelper.prototype.setMainColor = function (color) {
  99544. if (this.groundMaterial) {
  99545. this.groundMaterial.primaryColor = color;
  99546. }
  99547. if (this.skyboxMaterial) {
  99548. this.skyboxMaterial.primaryColor = color;
  99549. }
  99550. if (this.groundMirror) {
  99551. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99552. }
  99553. };
  99554. /**
  99555. * Setup the image processing according to the specified options.
  99556. */
  99557. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99558. if (this._options.setupImageProcessing) {
  99559. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99560. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99561. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99562. this._setupEnvironmentTexture();
  99563. }
  99564. };
  99565. /**
  99566. * Setup the environment texture according to the specified options.
  99567. */
  99568. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99569. if (this._scene.environmentTexture) {
  99570. return;
  99571. }
  99572. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99573. this._scene.environmentTexture = this._options.environmentTexture;
  99574. return;
  99575. }
  99576. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99577. this._scene.environmentTexture = environmentTexture;
  99578. };
  99579. /**
  99580. * Setup the background according to the specified options.
  99581. */
  99582. EnvironmentHelper.prototype._setupBackground = function () {
  99583. if (!this._rootMesh) {
  99584. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99585. }
  99586. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99587. var sceneSize = this._getSceneSize();
  99588. if (this._options.createGround) {
  99589. this._setupGround(sceneSize);
  99590. this._setupGroundMaterial();
  99591. this._setupGroundDiffuseTexture();
  99592. if (this._options.enableGroundMirror) {
  99593. this._setupGroundMirrorTexture(sceneSize);
  99594. }
  99595. this._setupMirrorInGroundMaterial();
  99596. }
  99597. if (this._options.createSkybox) {
  99598. this._setupSkybox(sceneSize);
  99599. this._setupSkyboxMaterial();
  99600. this._setupSkyboxReflectionTexture();
  99601. }
  99602. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99603. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99604. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99605. };
  99606. /**
  99607. * Get the scene sizes according to the setup.
  99608. */
  99609. EnvironmentHelper.prototype._getSceneSize = function () {
  99610. var _this = this;
  99611. var groundSize = this._options.groundSize;
  99612. var skyboxSize = this._options.skyboxSize;
  99613. var rootPosition = this._options.rootPosition;
  99614. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99615. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99616. }
  99617. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99618. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99619. });
  99620. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99621. if (this._options.sizeAuto) {
  99622. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99623. this._scene.activeCamera.upperRadiusLimit) {
  99624. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99625. skyboxSize = groundSize;
  99626. }
  99627. var sceneDiagonalLenght = sceneDiagonal.length();
  99628. if (sceneDiagonalLenght > groundSize) {
  99629. groundSize = sceneDiagonalLenght * 2;
  99630. skyboxSize = groundSize;
  99631. }
  99632. // 10 % bigger.
  99633. groundSize *= 1.1;
  99634. skyboxSize *= 1.5;
  99635. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99636. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99637. }
  99638. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99639. };
  99640. /**
  99641. * Setup the ground according to the specified options.
  99642. */
  99643. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  99644. var _this = this;
  99645. if (!this._ground) {
  99646. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  99647. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  99648. this._ground.parent = this._rootMesh;
  99649. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  99650. }
  99651. this._ground.receiveShadows = this._options.enableGroundShadow;
  99652. };
  99653. /**
  99654. * Setup the ground material according to the specified options.
  99655. */
  99656. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  99657. if (!this._groundMaterial) {
  99658. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  99659. }
  99660. this._groundMaterial.alpha = this._options.groundOpacity;
  99661. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  99662. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  99663. this._groundMaterial.primaryColor = this._options.groundColor;
  99664. this._groundMaterial.useRGBColor = false;
  99665. this._groundMaterial.enableNoise = true;
  99666. if (this._ground) {
  99667. this._ground.material = this._groundMaterial;
  99668. }
  99669. };
  99670. /**
  99671. * Setup the ground diffuse texture according to the specified options.
  99672. */
  99673. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  99674. if (!this._groundMaterial) {
  99675. return;
  99676. }
  99677. if (this._groundTexture) {
  99678. return;
  99679. }
  99680. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99681. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99682. return;
  99683. }
  99684. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99685. diffuseTexture.gammaSpace = false;
  99686. diffuseTexture.hasAlpha = true;
  99687. this._groundMaterial.diffuseTexture = diffuseTexture;
  99688. };
  99689. /**
  99690. * Setup the ground mirror texture according to the specified options.
  99691. */
  99692. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99693. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99694. if (!this._groundMirror) {
  99695. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99696. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99697. this._groundMirror.anisotropicFilteringLevel = 1;
  99698. this._groundMirror.wrapU = wrapping;
  99699. this._groundMirror.wrapV = wrapping;
  99700. this._groundMirror.gammaSpace = false;
  99701. if (this._groundMirror.renderList) {
  99702. for (var i = 0; i < this._scene.meshes.length; i++) {
  99703. var mesh = this._scene.meshes[i];
  99704. if (mesh !== this._ground &&
  99705. mesh !== this._skybox &&
  99706. mesh !== this._rootMesh) {
  99707. this._groundMirror.renderList.push(mesh);
  99708. }
  99709. }
  99710. }
  99711. }
  99712. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99713. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99714. };
  99715. /**
  99716. * Setup the ground to receive the mirror texture.
  99717. */
  99718. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99719. if (this._groundMaterial) {
  99720. this._groundMaterial.reflectionTexture = this._groundMirror;
  99721. this._groundMaterial.reflectionFresnel = true;
  99722. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99723. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99724. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99725. }
  99726. };
  99727. /**
  99728. * Setup the skybox according to the specified options.
  99729. */
  99730. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99731. var _this = this;
  99732. if (!this._skybox) {
  99733. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99734. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99735. }
  99736. this._skybox.parent = this._rootMesh;
  99737. };
  99738. /**
  99739. * Setup the skybox material according to the specified options.
  99740. */
  99741. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99742. if (!this._skybox) {
  99743. return;
  99744. }
  99745. if (!this._skyboxMaterial) {
  99746. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99747. }
  99748. this._skyboxMaterial.useRGBColor = false;
  99749. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99750. this._skyboxMaterial.enableNoise = true;
  99751. this._skybox.material = this._skyboxMaterial;
  99752. };
  99753. /**
  99754. * Setup the skybox reflection texture according to the specified options.
  99755. */
  99756. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99757. if (!this._skyboxMaterial) {
  99758. return;
  99759. }
  99760. if (this._skyboxTexture) {
  99761. return;
  99762. }
  99763. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99764. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99765. return;
  99766. }
  99767. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99768. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99769. this._skyboxTexture.gammaSpace = false;
  99770. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99771. };
  99772. /**
  99773. * Dispose all the elements created by the Helper.
  99774. */
  99775. EnvironmentHelper.prototype.dispose = function () {
  99776. if (this._groundMaterial) {
  99777. this._groundMaterial.dispose(true, true);
  99778. }
  99779. if (this._skyboxMaterial) {
  99780. this._skyboxMaterial.dispose(true, true);
  99781. }
  99782. this._rootMesh.dispose(false);
  99783. };
  99784. /**
  99785. * Default ground texture URL.
  99786. */
  99787. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99788. /**
  99789. * Default skybox texture URL.
  99790. */
  99791. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99792. /**
  99793. * Default environment texture URL.
  99794. */
  99795. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  99796. return EnvironmentHelper;
  99797. }());
  99798. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99799. })(BABYLON || (BABYLON = {}));
  99800. //# sourceMappingURL=babylon.environmentHelper.js.map
  99801. var BABYLON;
  99802. (function (BABYLON) {
  99803. /**
  99804. * This class is made for on one-liner static method to help creating particle systems.
  99805. */
  99806. var ParticleHelper = /** @class */ (function () {
  99807. function ParticleHelper() {
  99808. }
  99809. /**
  99810. * This is the main static method (one-liner) of this helper to create different particle systems.
  99811. * @param type This string represents the type to the particle system to create
  99812. * @param emitter The object where the particle system will start to emit from.
  99813. * @param scene The scene where the particle system should live.
  99814. * @param gpu If the system will use gpu.
  99815. * @returns the ParticleSystem created.
  99816. */
  99817. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99818. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99819. if (gpu === void 0) { gpu = false; }
  99820. return new Promise(function (resolve, reject) {
  99821. if (!scene) {
  99822. scene = BABYLON.Engine.LastCreatedScene;
  99823. ;
  99824. }
  99825. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99826. return reject("Particle system with GPU is not supported.");
  99827. }
  99828. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99829. var newData = JSON.parse(data.toString());
  99830. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  99831. }, undefined, undefined, undefined, function (req, exception) {
  99832. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99833. });
  99834. });
  99835. };
  99836. /**
  99837. * Static function used to create a new particle system from a IParticleSystemData
  99838. * @param data defines the source data
  99839. * @param scene defines the hosting scene
  99840. * @param emitter defines the particle emitter
  99841. * @returns a new ParticleSystem based on referenced data
  99842. */
  99843. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  99844. // Create a particle system
  99845. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  99846. // Where the particles come from
  99847. system.emitter = emitter; // the starting object, the emitter
  99848. ParticleHelper.UpdateSystem(system, data, scene);
  99849. return system;
  99850. };
  99851. /**
  99852. * Static function used to update a particle system from a IParticleSystemData
  99853. * @param system defines the particle system to update
  99854. * @param data defines the source data
  99855. * @param scene defines the hosting scene
  99856. */
  99857. ParticleHelper.UpdateSystem = function (system, data, scene) {
  99858. // Texture of each particle
  99859. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  99860. // Colors of all particles
  99861. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  99862. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  99863. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  99864. // Size of each particle (random between...
  99865. system.minSize = data.minSize;
  99866. system.maxSize = data.maxSize;
  99867. // Life time of each particle (random between...
  99868. system.minLifeTime = data.minLifeTime;
  99869. system.maxLifeTime = data.maxLifeTime;
  99870. // Emission rate
  99871. system.emitRate = data.emitRate;
  99872. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99873. system.blendMode = data.blendMode;
  99874. // Set the gravity of all particles
  99875. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  99876. // Angular speed, in radians
  99877. system.minAngularSpeed = data.minAngularSpeed;
  99878. system.maxAngularSpeed = data.maxAngularSpeed;
  99879. // Speed
  99880. system.minEmitPower = data.minEmitPower;
  99881. system.maxEmitPower = data.maxEmitPower;
  99882. system.updateSpeed = data.updateSpeed;
  99883. switch (data.emitterType) {
  99884. case "box":
  99885. if (!data.direction1 || !data.direction2) {
  99886. throw new Error("Directions are missing in this particle system.");
  99887. }
  99888. if (!data.minEmitBox || !data.maxEmitBox) {
  99889. throw new Error("EmitBox is missing in this particle system.");
  99890. }
  99891. 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));
  99892. break;
  99893. case "sphere":
  99894. system.createSphereEmitter(data.radius);
  99895. break;
  99896. case "directed_sphere":
  99897. if (!data.direction1 || !data.direction2) {
  99898. throw new Error("Directions are missing in this particle system.");
  99899. }
  99900. 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));
  99901. break;
  99902. case "cone":
  99903. system.createConeEmitter(data.radius, data.angle);
  99904. break;
  99905. default:
  99906. break;
  99907. }
  99908. };
  99909. /**
  99910. * Base Assets URL.
  99911. */
  99912. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  99913. return ParticleHelper;
  99914. }());
  99915. BABYLON.ParticleHelper = ParticleHelper;
  99916. })(BABYLON || (BABYLON = {}));
  99917. //# sourceMappingURL=babylon.particleHelper.js.map
  99918. var BABYLON;
  99919. (function (BABYLON) {
  99920. /**
  99921. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  99922. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  99923. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  99924. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  99925. */
  99926. var VideoDome = /** @class */ (function (_super) {
  99927. __extends(VideoDome, _super);
  99928. /**
  99929. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  99930. * @param name Element's name, child elements will append suffixes for their own names.
  99931. * @param urlsOrVideo defines the url(s) or the video element to use
  99932. * @param options An object containing optional or exposed sub element properties
  99933. */
  99934. function VideoDome(name, urlsOrVideo, options, scene) {
  99935. var _this = _super.call(this, name, scene) || this;
  99936. // set defaults and manage values
  99937. name = name || "videoDome";
  99938. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  99939. options.clickToPlay = Boolean(options.clickToPlay);
  99940. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  99941. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  99942. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  99943. // create
  99944. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  99945. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  99946. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  99947. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  99948. flat: false,
  99949. radius: options.size,
  99950. subdivisions: options.resolution,
  99951. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  99952. }, scene);
  99953. // configure material
  99954. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  99955. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  99956. material.reflectionTexture = _this._videoTexture;
  99957. material.useEquirectangularFOV = true;
  99958. material.fovMultiplier = 1.0;
  99959. // configure mesh
  99960. _this._mesh.material = material;
  99961. _this._mesh.parent = _this;
  99962. // optional configuration
  99963. if (options.clickToPlay) {
  99964. scene.onPointerUp = function () {
  99965. _this._videoTexture.video.play();
  99966. };
  99967. }
  99968. return _this;
  99969. }
  99970. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  99971. /**
  99972. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99973. * Also see the options.resolution property.
  99974. */
  99975. get: function () {
  99976. return this._material.fovMultiplier;
  99977. },
  99978. set: function (value) {
  99979. this._material.fovMultiplier = value;
  99980. },
  99981. enumerable: true,
  99982. configurable: true
  99983. });
  99984. /**
  99985. * Releases resources associated with this node.
  99986. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  99987. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  99988. */
  99989. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  99990. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  99991. this._videoTexture.dispose();
  99992. this._mesh.dispose();
  99993. this._material.dispose();
  99994. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  99995. };
  99996. return VideoDome;
  99997. }(BABYLON.Node));
  99998. BABYLON.VideoDome = VideoDome;
  99999. })(BABYLON || (BABYLON = {}));
  100000. //# sourceMappingURL=babylon.videoDome.js.map
  100001. var BABYLON;
  100002. (function (BABYLON) {
  100003. /**
  100004. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  100005. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  100006. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  100007. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  100008. */
  100009. var PhotoDome = /** @class */ (function (_super) {
  100010. __extends(PhotoDome, _super);
  100011. /**
  100012. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  100013. * @param name Element's name, child elements will append suffixes for their own names.
  100014. * @param urlsOfPhoto define the url of the photo to display
  100015. * @param options An object containing optional or exposed sub element properties
  100016. */
  100017. function PhotoDome(name, urlOfPhoto, options, scene) {
  100018. var _this = _super.call(this, name, scene) || this;
  100019. // set defaults and manage values
  100020. name = name || "photoDome";
  100021. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  100022. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  100023. // create
  100024. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  100025. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  100026. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  100027. flat: false,
  100028. radius: options.size,
  100029. subdivisions: options.resolution,
  100030. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  100031. }, scene);
  100032. // configure material
  100033. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100034. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100035. material.reflectionTexture = _this._photoTexture;
  100036. material.useEquirectangularFOV = true;
  100037. material.fovMultiplier = 1.0;
  100038. // configure mesh
  100039. _this._mesh.material = material;
  100040. _this._mesh.parent = _this;
  100041. return _this;
  100042. }
  100043. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100044. /**
  100045. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100046. * Also see the options.resolution property.
  100047. */
  100048. get: function () {
  100049. return this._material.fovMultiplier;
  100050. },
  100051. set: function (value) {
  100052. this._material.fovMultiplier = value;
  100053. },
  100054. enumerable: true,
  100055. configurable: true
  100056. });
  100057. /**
  100058. * Releases resources associated with this node.
  100059. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100060. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100061. */
  100062. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100063. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100064. this._photoTexture.dispose();
  100065. this._mesh.dispose();
  100066. this._material.dispose();
  100067. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100068. };
  100069. return PhotoDome;
  100070. }(BABYLON.Node));
  100071. BABYLON.PhotoDome = PhotoDome;
  100072. })(BABYLON || (BABYLON = {}));
  100073. //# sourceMappingURL=babylon.photoDome.js.map
  100074. 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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\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 float 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;\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 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 float size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float 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=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=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\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"};
  100075. 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};"};
  100076. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  100077. globalObject["BABYLON"] = BABYLON;
  100078. //backwards compatibility
  100079. if(typeof earcut !== 'undefined') {
  100080. globalObject["Earcut"] = {
  100081. earcut: earcut
  100082. };
  100083. }
  100084. return BABYLON;
  100085. });